1. 新建数据库和表
新建一个名为ssm的数据库,并创建一个user表,给user表插入几条数据
2. 新建一个maven工程
3. pom.xml导入坐标
这里只需要导入mybatis和连接mysql的包,另外可以导入log4j和junit的包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.ssm</groupId> <artifactId>mybatis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar </packaging>
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> </dependencies>
</project>
|
4. 创建实体类和DAO接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package com.ssm.domain;
import java.io.Serializable; import java.util.Date;
public class User implements Serializable { private Integer id; private String username; private Date birthday; private String sex; private String address;
public Integer getId() { return id; }
public void setId(Integer 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() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| package com.ssm.dao;
import com.ssm.domain.User; import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface IUserDao {
List<User> findAll();
void saveUser(User user);
void updateUser(User user);
void deleteUser(Integer userId); }
|
5. 创建Mybatis的主配置文件——SqlMapConfig.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?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> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments>
<mappers> <mapper resource="com/ssm/dao/IUserDao.xml"/> </mappers> </configuration>
|
6. 创建映射配置文件——IUserDao.xml
在配置文件中添加增删改查的sql语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <?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="com.ssm.dao.IUserDao"> <select id="findAll" resultType="com.ssm.domain.User"> select * from user </select>
<insert id="saveUser" parameterType="com.ssm.domain.User"> insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday}) </insert>
<update id="updateUser" parameterType="com.ssm.domain.User"> update user set username = #{username},address = #{address},birthday = #{birthday},sex = #{sex} where id = #{id} </update>
<delete id="deleteUser" parameterType="java.lang.Integer"> delete from user where id = #{uid} </delete> </mapper>
|
7. 编写测试类
因为增删改查的测试方法都要用到SqlSessionFactoryBuilder创建SqlSessionFactory工厂等等,所以把方法中相同的部分提取出来另写一个方法init(),包括方法最后的关闭资源操作也独立出来一个方法destroy()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| package com.ssm.test;
import com.ssm.dao.IUserDao; import com.ssm.domain.User; 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.After; import org.junit.Before; import org.junit.Test;
import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List;
public class MybatisTest {
private InputStream in; private SqlSession sqlSession; private IUserDao userDao;
@Before public void init()throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); sqlSession = factory.openSession(); userDao = sqlSession.getMapper(IUserDao.class); }
@After public void destroy() throws IOException { sqlSession.commit(); sqlSession.close(); in.close(); }
@Test public void testFindAll()throws Exception{ List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user); } }
@Test public void testSave() throws IOException { User user = new User(); user.setUsername("测试"); user.setAddress("成都市"); user.setBirthday(new Date()); user.setSex("男");
userDao.saveUser(user); }
@Test public void testUpdateUser() throws IOException { User user = new User(); user.setId(1); user.setUsername("张四"); user.setAddress("天津"); user.setBirthday(new Date()); user.setSex("女");
userDao.updateUser(user); }
@Test public void testDeleteUser() throws IOException { userDao.deleteUser(7); } }
|
8. Maven工程结构
9. 运行结果
这里以添加用户操作为实例
①在没有手动进行事务提交之前,程序虽然运行成功了,但是数据库中并没有插入数据。
输出结果中显示“Setting autocommit to false”,因为mybatis的自动提交是默认关闭的,所以执行完插入操作后进行了事务回滚。这时候数据库的user表中生成了key值但是并没有数据写入,就浪费了一个key值。当重新插入数据并提交事务后,主键的自增值不是+1,而是在上一条数据的基础上+2
②提交事务可以通过在添加操作后加入“sqlSession.commit();”或者在使用工厂生产SqlSession对象时,在openSession()方法中传入true
手动进行事务提交后,重新执行代码输出结果显示“Committing JDBC Connection”,查看user表,数据以及成功插入