package cn.edu.hpu.mybatis.mapper; import cn.edu.hpu.mybatis.PO.User; //用户管理的Dao接口 public interface UserMapper { //根据Id查询用户信息 public User findUserById(int id) throws Exception; //添加用户信息 public void insertUser(User user) throws Exception; //删除用户信息 public void deleteUser(int id) throws Exception; //修改用户信息 public void updateUser(User user) throws Exception; //根据姓名查找用户 public List<User> findUserByUserName(String username) throws Exception; }
<?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"> <!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 注意:使用mapper代理方法开发,namespace有特殊重要的作用,就是对应的mapper接口地址 --> <mapper namespace="cn.edu.hpu.mybatis.mapper.UserMapper"> <!-- 在映射文件中配置很多sql语句 --> <!-- 需求:通过id查询用户表的记录 --> <!-- 通过select执行数据库查询, id:标示映射文件中的sql,成为Statement的id 将sql语句封装到mappedStatement对象中,所以将id称为statement的id, parameterType:指定输入参数的类型, #{}标示一个占位符, #{id}其中id表示接收输入参数的名称,如果输入参数是简单类型,那么#{}中的值可以任意(如value)。 resultType:指定sql输出结果的映射的java对象类型, select指定resultType表示将单条记录映射成java对象--> <select id="findUserById" parameterType="int" resultType="cn.edu.hpu.mybatis.PO.User"> SELECT * FROM USER WHERE id=#{id} </select> <!-- ${}:表示拼接sql串,将接收到的参数内容不加任何修饰拼接在sql中。 使用${}拼接sql,引起sql注入。 ${}中只能使用value--> <select id="findUserByUserName" parameterType="java.lang.String" resultType="cn.edu.hpu.mybatis.PO.User"> select * from user where username like '%${value}%' </select> <!-- 添加用户 parameterType:指定输入参数类型是pojo(包括用户信息) #{}中指定POJO的属性名,接收到POJO对象的属性值,mybatis通过OGNL获取对象的属性 --> <insert id="insertUser" parameterType="cn.edu.hpu.mybatis.PO.User"> <!-- 将插入数据的主键返回,返回到user对象中。 SELECT_INSERT_ID():得到刚insert进去的主键值,只适用于自增主键 KeyProperty:将查询到主键值设置到parameterType指定对象的哪个属性。 order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序 --> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT LAST_INSERT_ID() </selectKey> <!-- 使用MySql的UUID来生成主键 执行过程: 首先通过uuid()得到主键,将主键设置到user对象的id属性中 其次在insert执行时,从user对象中取出id属性值 <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String"> SELECT uuid() </selectKey> insert into user(id,birthday,sex,address) value(#{id},#{birthday,jdbcType=DATE},#{sex},#{address})--> insert into user(username,birthday,sex,address) value(#{username},#{birthday,jdbcType=DATE},#{sex},#{address}) </insert> <!-- 删除用户 --> <delete id="deleteUser" parameterType="java.lang.Integer"> delete from user where id=#{id} </delete> <!-- 更新用户 分析: 需要传入用户的id,需要传入用户的更新信息. parameterType指定user对象,包括id和更新信息(注意:id必须存在) #{id}:从输入user对象中获取id属性值--> <update id="updateUser" parameterType="cn.edu.hpu.mybatis.PO.User"> update user set username=#{username},birthday=#{birthday,jdbcType=DATE},sex=#{sex},address=#{address} where id=#{id} </update> </mapper>
<mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers>
User user=sqlSession.selectOne("test.findUserById",id); sqlSession.insert("test.insertUser",user);
package cn.edu.hpu.mybatis.test; import java.io.InputStream; 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.Before; import org.junit.Test; import cn.edu.hpu.mybatis.PO.User; import cn.edu.hpu.mybatis.mapper.UserMapper; public class UserMapperTest { private SqlSessionFactory sqlSessionFactory; //注解Before是在执行本类所有测试方法之前先调用这个方法 @Before public void setup() throws Exception{ //创建SqlSessionFactory String resource="SqlMapConfig.xml"; //将配置文件加载成流 InputStream inputStream = Resources.getResourceAsStream(resource); //创建会话工厂,传入mybatis配置文件的信息 sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testFindUserById() throws Exception{ SqlSession sqlSession=sqlSessionFactory.openSession(); //创建UserMapper代理对象 UserMapper userMapper=sqlSession.getMapper(UserMapper.class); //调用userMapper的方法 User user=userMapper.findUserById(1); System.out.println(user.getUsername()); } }
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 14069849. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.Connection@d6b059] DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE id=? DEBUG [main] - ==> Parameters: 1(Integer) DEBUG [main] - <== Total: 1
@Test public void testFindUserByUserName() throws Exception{ SqlSession sqlSession=sqlSessionFactory.openSession(); //创建UserMapper代理对象 UserMapper userMapper=sqlSession.getMapper(UserMapper.class); //调用userMapper的方法 List<User> users=userMapper.findUserByName("张三"); for (int i = 0; i < users.size(); i++) { User user=(User)users.get(i); System.out.println(user.getId()+":"+user.getUsername()); } }测试结果:
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 1668655. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.Connection@19762f] DEBUG [main] - ==> Preparing: select * from user where username like '%张三%' DEBUG [main] - ==> Parameters: DEBUG [main] - <== Total: 2
注意:持久层方法的参数可以包装类型、map。。。,service方法中建议不要使用包装类型(不利于业务层的可扩展)。
转载请注明出处:http://blog.csdn.net/acmman/article/details/46488843