mybatis执行CRUD操作的两种方式配置和注解
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis执行CRUD操作的两种方式配置和注解相关的知识,希望对你有一定的参考价值。
一、使用MyBatis对表执行CRUD操作——基于XML的实现
1、定义sql映射xml文件
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.mi.mapping.UserInfoMapper"> <select id="getUser" resultType="com.mi.entity.User"> SELECT id,user_name userName,age FROM user_t where id=1 </select> <!-- 创建用户(Create) --> <insert id="addUser" parameterType="com.mi.entity.User"> insert into user_t(id,user_name,password,age) values(11,#{userName},0,#{age}) </insert> <!-- 删除用户(Remove) --> <delete id="deleteUser" parameterType="int"> delete from user_t where id=#{id} </delete> <!-- 修改用户(Update) --> <update id="updateUser" parameterType="com.mi.entity.User"> update user_t set user_name=#{userName},age=#{age} where id=#{id} </update> <!-- 查询全部用户--> <select id="getAllUsers" resultType="com.mi.entity.User"> select * from user_t </select> </mapper>
package com.mi.demo; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.mi.entity.User; public class TestCRUDByXmlMapper { @Test public void testAdd(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(true); String statement = "com.mi.mapping.UserInfoMapper.addUser"; User user = new User(); user.setUserName("xinzhao"); user.setAge(20); int insertResult = sqlSession.insert(statement,user); sqlSession.close(); System.out.println(insertResult); } @Test public void testUpdate(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(true); String statement = "com.mi.mapping.UserInfoMapper.updateUser"; User user = new User(); user.setId(11); user.setUserName("xinzhao"); user.setAge(22); int result = sqlSession.update(statement, user); sqlSession.close(); System.out.println(result); } @Test public void testDelete(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(true); String statement = "com.mi.mapping.UserInfoMapper.deleteUser"; User user = new User(); user.setId(11); int result = sqlSession.delete(statement, user); sqlSession.close(); System.out.println(result); } @Test public void testGetAll(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(true); String statement = "com.mi.mapping.UserInfoMapper.getAllUsers"; List<User> userList = sqlSession.selectList(statement); sqlSession.close(); for(User user : userList){ System.out.println(user.getUserName()); } } }
二、使用MyBatis对表执行CRUD操作——基于注解的实现
1、定义sql映射的接口
UserMapper接口的代码如下:
package com.mi.demo; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.mi.entity.User; public interface UserMapper { @Insert(" insert into user_t(id,user_name,password,age) values(11,#{userName},0,#{age})") public int addUser(User user); @Delete("delete from user_t where id=#{id}") public int deleteById(int id); @Update("update user_t set user_name=#{userName},age=#{age} where id=#{id}") public int update(User user); @Select("SELECT id,user_name userName,age FROM user_t where id=1") public User getById(int id); @Select("select * from user_t") public List<User> getAll(); }
2、在conf.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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置数据库连接信息 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost/mi" /> <property name="username" value="root" /> <property name="password" value="dbdaocom" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/mi/mapping/UserInfoMapper.xml"/><!-- 注册userMapper.xml文件, --> <mapper class="com.mi.demo.UserMapper"/><!-- 注册UserMapper映射接口--> </mappers> </configuration>
单元测试类的代码如下:
package com.mi.demo; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.mi.entity.User; public class TestCRUDByAnnotationMapper { @Test public void testAdd() { SqlSession sqlSession = MyBatisUtil.getSqlSession(true); // 得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来 UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(); user.setUserName("用户xdp"); user.setAge(20); int result = mapper.addUser(user); sqlSession.close(); System.out.println(result); } /** * ...the end */ }
用到的MyBatisUtil工具类代码如下:
package com.mi.demo; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { /** * 获取SqlSessionFactory * * @return SqlSessionFactory */ public static SqlSessionFactory getSqlSessionFactory() { // mybatis的配置文件 String resource = "conf.xml"; // 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件) InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource); // 构建sqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); return sessionFactory; } /** * 获取SqlSession * * @return SqlSession */ public static SqlSession getSqlSession() { return getSqlSessionFactory().openSession(); } /** * 获取SqlSession * * @param isAutoCommit * true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务 * false表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession. * commit()提交事务 * @return SqlSession */ public static SqlSession getSqlSession(boolean isAutoCommit) { return getSqlSessionFactory().openSession(isAutoCommit); } }
以上是关于mybatis执行CRUD操作的两种方式配置和注解的主要内容,如果未能解决你的问题,请参考以下文章