Home > Database > Mysql Tutorial > Mybatis入门案例--增删改查

Mybatis入门案例--增删改查

WBOY
Release: 2016-06-07 15:23:09
Original
1312 people have browsed it

一、先建一个数据库test,再建一张user表,表里有两个字段:id 是自增长,name。 二、新建一个java项目,导入两个jar包:mysql-connector-java-5.1.17-bin.jar 和 mybatis-3.0.4.jar。 三、在src下建一个包:com.cb 四、在com.cb包下面有四个文件,可以直接

一、先建一个数据库test,再建一张user表,表里有两个字段:id 是自增长,name。

二、新建一个java项目,导入两个jar包:mysql-connector-java-5.1.17-bin.jar 和 mybatis-3.0.4.jar。

三、在src下建一个包:com.cb

四、在com.cb包下面有四个文件,可以直接复制粘贴进去:

1、 User.java

package com.cb;
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(){

}
}

2、configuration.xml


br> "http://mybatis.org/dtd/mybatis-3-config.dtd">



















3、User.xml


br> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">



insert into user(name)
values(#{name})



delete from user where id=#{id}



update user set name=#{name} where id=#{id}





4、 Test.java

package com.cb;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Test {

@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException{
String resource = "com/cb/configuration.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
try {
//增加一条新的记录
User user=new User();
user.setName("wangwu");
session.insert("com.cb.User.addOneUser",user);
session.commit();

//删除一条记录
/*session.delete("com.cb.User.deleteOneUser",11);
session.commit();*/

//更新一条数据
/*User user=new User();
user.setName("lisi");
user.setId(2);
session.update("com.cb.User.updateOneUser",user);
session.commit();*/

//按条件查询一条数据
/*User user = (User) session.selectOne("com.cb.User.selectOneUser",8);
System.out.println("id\tname");
System.out.println(user.getId()+"\t"+user.getName());*/

//查询表的全部数据
ArrayList list = (ArrayList) session.selectList("com.cb.User.selectAllUser");
for(int i=0;i System.out.println(list.get(i).getId()+"\t"+list.get(i).getName());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
session.close();
}
}
}


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template