Mybatis入门学习篇(二)之基于注解的增删改查

工程环境: JDK1.8 + Mybatis3 + JUnit + Mysql 




1. 在数据库中建表

学生表:

create table student(id int auto_increment primary key,name varchar(10) unique, age int);


2.  运用Mybatis Generator反向生成model,mapper

请参考Mybatis入门学习篇(一)之Mybatis Generator使用

Model-Student: 

[java]  view plain  copy
  1. package com.zjh.model;  
  2.   
  3. public class Student {  
  4.     private Integer id;  
  5.   
  6.     private String name;  
  7.   
  8.     private Integer age;  
  9.   
  10.     public Integer getId() {  
  11.         return id;  
  12.     }  
  13.   
  14.     public void setId(Integer id) {  
  15.         this.id = id;  
  16.     }  
  17.   
  18.     public String getName() {  
  19.         return name;  
  20.     }  
  21.   
  22.     public void setName(String name) {  
  23.         this.name = name == null ? null : name.trim();  
  24.     }  
  25.   
  26.     public Integer getAge() {  
  27.         return age;  
  28.     }  
  29.   
  30.     public void setAge(Integer age) {  
  31.         this.age = age;  
  32.     }  
  33. }  
Mapper-StudentMapper:

[java]  view plain  copy
  1. package com.zjh.mapper;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.ibatis.annotations.Delete;  
  6. import org.apache.ibatis.annotations.Insert;  
  7. import org.apache.ibatis.annotations.Param;  
  8. import org.apache.ibatis.annotations.Result;  
  9. import org.apache.ibatis.annotations.Select;  
  10. import org.apache.ibatis.annotations.SelectKey;  
  11. import org.apache.ibatis.annotations.Update;  
  12. import org.apache.ibatis.mapping.StatementType;  
  13. import org.apache.ibatis.type.JdbcType;  
  14.   
  15. import com.zjh.model.Student;  
  16.   
  17. public interface StudentMappper {  
  18.     //基于注解的增删改查  
  19.     @Update("update student set name = #{student.name},age = #{student.age} where id = #{student.id}")  
  20.     @Result(jdbcType = JdbcType.INTEGER)  
  21.     public int update(@Param("student") Student student);  
  22.   
  23.     @Select("select * from student where name like '%'||#{name}||'%'")  
  24.     @Result(javaType = Student.class)  
  25.     public List<Student> findByName(@Param("name") String name);  
  26.   
  27.     @Select("select * from student where age = #{age}")  
  28.     @Result(javaType = Student.class)  
  29.     public List<Student> findByAge(@Param("age") Integer age);  
  30.   
  31.     @Insert("insert into student(id,name,age) values(null,#{student.name},#{student.age})")  
  32.     @Result(jdbcType = JdbcType.INTEGER)  
  33.     @SelectKey(keyProperty = "student.id", keyColumn = "id", statement = "select @@identity as id", statementType = StatementType.STATEMENT, resultType = Integer.class, before = false)  
  34.     public int insert(@Param("student") Student student);  
  35.   
  36.     @Delete("delete from student where id = #{student.id}")  
  37.     @Result(jdbcType = JdbcType.INTEGER)  
  38.     public int delete(@Param("student") Student student);  
  39.   
  40.     //以下由工具自动生成,已自动生成配置信息  
  41.     int deleteByPrimaryKey(Integer id);  
  42.   
  43.     int insertSelective(Student record);  
  44.   
  45.     Student selectByPrimaryKey(Integer id);  
  46.   
  47.     int updateByPrimaryKeySelective(Student record);  
  48.   
  49.     int updateByPrimaryKey(Student record);  
  50. }  
Mapper-StudentMapper.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="com.zjh.mapper.StudentMapper">  
  4.     <resultMap id="BaseResultMap" type="com.zjh.model.Student">  
  5.         <id column="id" property="id" jdbcType="INTEGER" />  
  6.         <result column="name" property="name" jdbcType="VARCHAR" />  
  7.         <result column="age" property="age" jdbcType="INTEGER" />  
  8.     </resultMap>  
  9.     <sql id="Base_Column_List">  
  10.         id, name, age  
  11.     </sql>  
  12.     <select id="selectByPrimaryKey" resultMap="BaseResultMap"  
  13.         parameterType="java.lang.Integer">  
  14.         select  
  15.         <include refid="Base_Column_List" />  
  16.         from student  
  17.         where id = #{id,jdbcType=INTEGER}  
  18.     </select>  
  19.     <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">  
  20.         delete from student  
  21.         where id = #{id,jdbcType=INTEGER}  
  22.     </delete>  
  23.     <insert id="insert" parameterType="com.zjh.model.Student">  
  24.         insert into student (id, name, age  
  25.         )  
  26.         values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},  
  27.         #{age,jdbcType=INTEGER}  
  28.         )  
  29.     </insert>  
  30.     <insert id="insertSelective" parameterType="com.zjh.model.Student">  
  31.         insert into student  
  32.         <trim prefix="(" suffix=")" suffixOverrides=",">  
  33.             <if test="id != null">  
  34.                 id,  
  35.             </if>  
  36.             <if test="name != null">  
  37.                 name,  
  38.             </if>  
  39.             <if test="age != null">  
  40.                 age,  
  41.             </if>  
  42.         </trim>  
  43.         <trim prefix="values (" suffix=")" suffixOverrides=",">  
  44.             <if test="id != null">  
  45.                 #{id,jdbcType=INTEGER},  
  46.             </if>  
  47.             <if test="name != null">  
  48.                 #{name,jdbcType=VARCHAR},  
  49.             </if>  
  50.             <if test="age != null">  
  51.                 #{age,jdbcType=INTEGER},  
  52.             </if>  
  53.         </trim>  
  54.     </insert>  
  55.     <update id="updateByPrimaryKeySelective" parameterType="com.zjh.model.Student">  
  56.         update student  
  57.         <set>  
  58.             <if test="name != null">  
  59.                 name = #{name,jdbcType=VARCHAR},  
  60.             </if>  
  61.             <if test="age != null">  
  62.                 age = #{age,jdbcType=INTEGER},  
  63.             </if>  
  64.         </set>  
  65.         where id = #{id,jdbcType=INTEGER}  
  66.     </update>  
  67.     <update id="updateByPrimaryKey" parameterType="com.zjh.model.Student">  
  68.         update student  
  69.         set name = #{name,jdbcType=VARCHAR},  
  70.         age = #{age,jdbcType=INTEGER}  
  71.         where id = #{id,jdbcType=INTEGER}  
  72.     </update>  
  73. </mapper>  


3.  配置mybatis需要的信息

在根目录下新建xml文件,取名为mybatis-config.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <!DOCTYPE configuration   
  3.     PUBLIC "-//mybatis.org//DTD Config 3.0//EN"   
  4.     "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  5.   
  6. <configuration>  
  7.     <settings>  
  8.         <setting name="cacheEnabled" value="false" />  
  9.         <setting name="useGeneratedKeys" value="true" />  
  10.         <setting name="defaultExecutorType" value="REUSE" />  
  11.     </settings>  
  12.   
  13.     <environments default="development">  
  14.         <environment id="development">  
  15.             <!-- 配置事务类型 -->  
  16.             <transactionManager type="jdbc" />  
  17.             <dataSource type="POOLED">  
  18.                 <!--数据库驱动 -->  
  19.                 <property name="driver" value="com.mysql.jdbc.Driver" />  
  20.                 <!-- 数据库URL -->  
  21.                 <property name="url" value="jdbc:mysql://localhost:3306/mybatistest" />  
  22.                 <!-- 数据库用户名 -->  
  23.                 <property name="username" value="root" />  
  24.                 <!-- 数据库密码 -->  
  25.                 <property name="password" value="admin" />  
  26.             </dataSource>  
  27.         </environment>  
  28.     </environments>  
  29.       
  30.  <mappers>  
  31.         <mapper resource="com/zjh/mapper/StudentMapper.xml"/>  
  32.     </mappers>  
  33.       
  34. </configuration>  


4. 测试

这里测试使用的是Junit

首先是获得Session

[java]  view plain  copy
  1. public SqlSession getSession() {  
  2.         //通过Resources读取mybatis配置文件  
  3.         try (Reader resource = Resources  
  4.                 .getResourceAsReader("mybatis-config.xml")) {  
  5.             //根据配置文件建立SessioFactory  
  6.             SqlSessionFactory factory = new SqlSessionFactoryBuilder()  
  7.                     .build(resource);  
  8.             //将StudentMapper在SessioFactory中注册  
  9.             factory.getConfiguration().addMapper(StudentMappper.class);  
  10.             //获取session  
  11.             return factory.openSession();  
  12.         } catch (IOException e) {  
  13.             // TODO Auto-generated catch block  
  14.             e.printStackTrace();  
  15.             return null;  
  16.         }  
下面依次做插入,删除,更新,查询的测试

[java]  view plain  copy
  1. @org.junit.Test  
  2.     public void insert() throws IOException {  
  3.         SqlSession session = getSession();  
  4.   
  5.         Student student = new Student();  
  6.         student.setAge(21);  
  7.         student.setName("zjh63248");  
  8.   
  9.         StudentMappper dao = session.getMapper(StudentMappper.class);  
  10.         System.out.println(dao.insert(student));  
  11.         session.commit();  
  12.         session.close();  
  13.         System.out.println(student.getId());  
  14.     }  
  15.   
  16.     @org.junit.Test  
  17.     public void select() {  
  18.         SqlSession session = getSession();  
  19.         StudentMappper dao = session.getMapper(StudentMappper.class);  
  20.   
  21.         List<Student> list = dao.findByName("zjh");  
  22.         for (Student s : list) {  
  23.             System.out.println(s.getName() + "的年龄是" + s.getAge());  
  24.         }  
  25.     }  
  26.   
  27.     @org.junit.Test  
  28.     public void delete() {  
  29.         SqlSession session = getSession();  
  30.         StudentMappper dao = session.getMapper(StudentMappper.class);  
  31.   
  32.         Student student = new Student();  
  33.         student.setAge(21);  
  34.         student.setName("zjh63248");  
  35.         student.setId(26);  
  36.   
  37.         System.out.println(dao.delete(student));  
  38.         session.commit();  
  39.         session.close();  
  40.     }  
  41.   
  42.     @org.junit.Test  
  43.     public void update() {  
  44.         SqlSession session = getSession();  
  45.         StudentMappper dao = session.getMapper(StudentMappper.class);  
  46.   
  47.         Student student = new Student();  
  48.         student.setAge(21);  
  49.         student.setName("zjh");  
  50.         student.setId(27);  
  51.   
  52.         System.out.println(dao.update(student));  
  53.         session.commit();  
  54.         session.close();  
  55.     }  

到此结束,期间遇到的问题,会在下一章节做记录.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值