Mybatis配置过程——增删改查实例
一、配置过程:
1. 创建一个项目
2. 导入所有的Jar包
数据库驱动
MyBatis核心包
MyBatis依赖包
JUnit
3. 配置log4j
4. 创建MyBatis的核心配置文件 SqlMapConfig.xml
5. 创建实体类
实体类定义的规则
1.实体类的属性要与数据库中的字段相对应
2.属性要私有化,同时提供每个属性的setter getter;
3.实体类必须要有无参的构造方法
6. 创建Mapper配置
namespace命名空间,隔离不同的SQL操作
SQL操作节点: select update insert delete CRUD
id:指定一个唯一的名称
parameterType:指定参数的类型
resultType:指定返回结果的类型
SQL语句:参数的传递有两种方式,1. #{} 2. ${}
当有多个参数需要传递给SQL语句时,先将这些参数封装到实体类中,以对象的方式传递
此时,可以使用#{属性名} ${属性名}来访问这些参数
7. 在SqlMapConfig.xml中声明一下User.xml
8. 编写测试代码
1.创建SqlSessionFactory
2.创建SqlSession
3.根据映射关系调用SQL
4.处理
5.关闭SqlSession
二、实例:
使用Mybaits对User表进行CRUD
查询:根据ID查询, 根据用户名称模糊查询
1.创建数据库表user
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` varchar(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256)DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
)
2.创建java工程,然后加入mybatis核心包、依赖包、数据驱动包。
3.在src下创建log4j.properties如下(此步骤可以省略,主要是为打印log日志,可查看执行的sql):
#Global logging configuration
log4j.rootLogger=DEBUG,stdout
#Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p[%t]-%m%n
4. 在src下创建mybatis核心配置文件SqlMapConfig.xml,如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis,org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC" />
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="User.xml"/>
</mappers>
</configuration>
5. Po类作为mybatis进行sql映射使用,po类通常与数据库表对应,User.java如下:
package com.mybatis.po;
import java.text.SimpleDateFormat;
import java.util.Date;
public class User {
private int id;
private String username;
private Date birthday;
private String sex;
private String address;
public User(){
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
SimpleDateFormat bir = new SimpleDateFormat("yyyy-MM-dd");
return "User [id=" + id + ", username=" + username + ", birthday=" + bir.format(birthday) + ", sex=" + sex + ", address="
+ address + "]";
}
}
6.在src下创建sql映射文件User.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis,org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<select id="findUserById" parameterType="int" resultType="com.mybatis.po.User">
select * from user where id = #{id}
</select>
<select id="findUserByName" parameterType="String" resultType="com.mybatis.po.User">
select * from user where username like '%${value}%'
</select>
<select id="addUser" parameterType="com.mybatis.po.User" resultType="int">
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
<!--insert into user(username,sex,address) values(#{username},#{sex},#{address}) -->
</select>
<update id="updateUserById" parameterType="com.mybatis.po.User" >
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id};
<!--update user set username=#{username},sex=#{sex},address=#{address} where id=#{id}; -->
</update>
<delete id="deleteUserById" parameterType="int" >
delete from user where id=#{id};
</delete>
</mapper>
7.在SqlMapConfig.xml中声明一下User.xml: <mappers>
<mapper resource="User.xml"/>
</mappers>
8. 编写测试代码 MainTest.java
package com.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.mybatis.po.User;
public class MainTest {
@Test
//根据ID查询
public void findUserById() throws IOException{
String resource="SqlMapConfig.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession=factory.openSession();
Scanner sc=new Scanner(System.in);
System.out.println("请输入id:");
int id=sc.nextInt();
User user=openSession.selectOne("test.findUserById", id);
System.out.println(user);
openSession.close();
}
@Test
//用户名关键字查询
public void findUserByName() throws IOException{
String resource="SqlMapConfig.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession=factory.openSession();
System.out.println("请输入用户名关键字:");
Scanner sc=new Scanner(System.in);
String username=sc.next();
List<User>list=openSession.selectList("test.findUserByName",username);
System.out.println(list);
openSession.close();
}
@Test
//添加用户
public void addUser() throws IOException, ParseException{
String resource="SqlMapConfig.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession=factory.openSession();
Scanner sc=new Scanner(System.in);
System.out.println("请输入用户名:");
String username=sc.next();
System.out.println("请输入生日:");
String birthday1=sc.next();
DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
Date birthday=format.parse(birthday1);
System.out.println("请输入性别:");
String sex=sc.next();
System.out.println("请输入地址:");
String address=sc.next();
User user=new User();
user.setUsername(username);
user.setBirthday(birthday);
user.setSex(sex);
user.setAddress(address);
user.getId();
int result=openSession.insert("test.addUser", user);
openSession.commit();
System.out.println(result);
openSession.close();
}
@Test
//修改用户信息
public void updateUserById() throws IOException{
String resource="SqlMapConfig.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession=factory.openSession();
Scanner sc=new Scanner(System.in);
System.out.println("请输入id:");
int id=sc.nextInt();
User user=openSession.selectOne("test.findUserById", id);
System.out.println("请输入用户名:");
String username=sc.next();
System.out.println("请输入生日:");
String birthday1=sc.next();
DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
Date birthday = null;
try {
birthday = format.parse(birthday1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("请输入性别:");
String sex=sc.next();
System.out.println("请输入地址:");
String address=sc.next();
user.setUsername(username);
user.setBirthday(birthday);
user.setSex(sex);
user.setAddress(address);
user.getId();
openSession.update("test.updateUserById", user);
openSession.commit();
System.out.println(user);
openSession.close();
}
@Test
//根据ID删除用户
public void deleteUserById() throws IOException{
String resource="SqlMapConfig.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession=factory.openSession();
System.out.println("请输入id:");
Scanner sc=new Scanner(System.in);
int id=sc.nextInt();
openSession.delete("test.deleteUserById", id);
openSession.commit();
openSession.close();
}
public static void main(String[] args) throws IOException, ParseException{
while(true){
System.out.println("***************************************************");
System.out.println("1.ID查询 2.用户名关键字查询 3.添加用户 4.修改用户信息 5.删除用户 6.退出");
System.out.println("***************************************************");
MainTest mainTest=new MainTest();
Scanner sc=new Scanner(System.in);
System.out.println("请输入要进行操作的序号:");
int num=sc.nextInt();
switch (num) {
case 1:
mainTest.findUserById();
break;
case 2:
mainTest.findUserByName();
break;
case 3:
mainTest.addUser();
break;
case 4:
mainTest.updateUserById();
break;
case 5:mainTest.deleteUserById();
break;
case 6:System.out.println("感谢使用!");
return;
default:
System.out.println("输入有误");
break;
}
}
}
}
9.项目结构: