创建maven项目,并分别添加依赖,junit,mysql,mybatis(3.4.6)
-
在resouces下创建mybatis的配置文件
<?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="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3307/mysqls?serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="LKT981016"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/pojo/UsersMapper.xml"/> </mappers> </configuration>
-
数据库文件 db.sql
CREATE TABLE `user` ( `uid` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) NOT NULL, `password` varchar(20) NOT NULL, `age` int(11) DEFAULT NULL, `addr` varchar(50) DEFAULT NULL, PRIMARY KEY (`uid`), UNIQUE KEY `username` (`username`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1
-
JavaBean文件 User.java
public class User { private int uid; private String username; private String password; private int age; private String addr; public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } @Override public String toString() { final StringBuffer sb = new StringBuffer("User{"); sb.append("uid=").append(uid); sb.append(", username='").append(username).append('\''); sb.append(", password='").append(password).append('\''); sb.append(", age=").append(age); sb.append(", addr='").append(addr).append('\''); sb.append('}'); return sb.toString(); } }
-
在com.pojo的包下创建UserMapper.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="com.qfedu.pojo.UserMapper"> <select id="selectUser" resultType="com.qfedu.pojo.User"> select * from user </select> <select id="selectUserCount" resultType="int"> select count(1) from user; </select> <select id="selectUsersByPage1" resultType="com.qfedu.pojo.User"> select * from user limit 3 </select> <select id="selectUsersByPage2" resultType="com.qfedu.pojo.User"> select * from user limit #{pageSize} </select> <select id="selectUsersByPage3" resultType="com.qfedu.pojo.User"> select * from user limit #{startIndex}, #{pageSize} </select> <delete id="saveUser"> insert into user values(null, #{username}, #{password}, #{age}, #{addr}); </delete> <delete id="deleteUserByUid"> delete from user where uid = #{uid} </delete> <update id="updateUser"> update user set username= #{username}, password=#{password}, age = #{age}, addr = #{addr} where uid = #{uid}; </update> </mapper>
-
测试类 TestUser.java
public class TestUser { private SqlSessionFactory sf = null; private SqlSession session = null; @Before public void setUp(){ try { sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml")); session = sf.openSession(true); } catch (IOException e) { e.printStackTrace(); } } @After public void tearDown(){ if(session != null){ session.close(); session = null; } } @Test public void testGetAllUsers(){ List<User> users = session.selectList("com.pojo.UserMapper.selectUser"); for (User u : users) { System.out.println(u); } } @Test public void testGetAllUsersCount(){ Integer count = session.selectOne("com.pojo.UserMapper.selectUserCount"); System.out.println(count); } @Test public void testGetUsersByPage1(){ List<User> users = session.selectList("com.pojo.UserMapper.selectUsersByPage1"); for (User u : users) { System.out.println(u); } } @Test public void testGetUsersByPage2(){ List<User> users = session.selectList("com.pojo.UserMapper.selectUsersByPage2", 9); for (User u : users) { System.out.println(u); } } @Test public void testGetUsersByPage3(){ Map<String, Integer> map = new HashMap<>(); map.put("startIndex", 10); map.put("pageSize", 5); List<User> users = session.selectList("com.pojo.UserMapper.selectUsersByPage3", map); for (User u : users) { System.out.println(u); } } @Test public void testSaveUser(){ User u = new User(); u.setUsername("lkt"); u.setPassword("888888"); u.setAddr("suzhou"); u.setAge(20); int result = session.insert("com.pojo.UserMapper.saveUser", u); System.out.println(result); } }
-
注意事项
-
UserMapper的映射文件:
- namespace和id在整个项目中,必须要保证唯一
- namespace+id找到的是唯一的sql语句,标签可能不对应,但是不影响执行结果,但是还是需要规范各个标签
-
TestUser.java
- 创建SqlSession对象的时候,SqlSessionFactory对象的openSession()方法不包含参数,则使用事务手动提交,做完增删改操作后,需要调用SqlSession对象的commit()方法完成事务的提交。如果openSession()方法包含有一个true,代表自动提交生效,我们做完增删改操作时候,就完成了对应的增删改功能。openSession()方法默认的提交方式为手动提交
- 该类活用了junit的生命周期方法,每个测试方法执行之前都会调用标注有@Before注解的setUp()方法完成环境的准备工作,每个方法完成之后都自动的执行标注有@After注解的tearDown()方法完成资源的释放工作
- SqlSession是mybatis中的核心对象,使用该对象即可完成对于所有操作的crud功能,里面有对应的方法,selectList(),查询列表(集合),selectOne()查询单个对象,insert(),delete,update()分别对应增删改功能。这三个方法的返回值均为受影响的行数
- 每次使用完SqlSession对象之后,使用close()方法将SqlSession对象关闭,不建议关闭SqlSessionFactory对象
- 关于传递参数
- 传递单个值,sql语句里面的占位符可以任意写
- 多个值,可以使用Map来传值,map中的key要与sql语句中的占位符一致
- 对象传值,sql语句中的字段值与对象的属性名一致
- 零散值的传递,可以使用两种方式arg0, arg1,...或者param1,param2...
-
MyBatis的单表的CRUD
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...