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: 

 

package com.zjh.model;

public class Student {
	private Integer id;

	private String name;

	private Integer age;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name == null ? null : name.trim();
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}
}

Mapper-StudentMapper:

 

 

package com.zjh.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.type.JdbcType;

import com.zjh.model.Student;

public interface StudentMappper {
	//基于注解的增删改查
	@Update("update student set name = #{student.name},age = #{student.age} where id = #{student.id}")
	@Result(jdbcType = JdbcType.INTEGER)
	public int update(@Param("student") Student student);

	@Select("select * from student where name like '%'||#{name}||'%'")
	@Result(javaType = Student.class)
	public List<Student> findByName(@Param("name") String name);

	@Select("select * from student where age = #{age}")
	@Result(javaType = Student.class)
	public List<Student> findByAge(@Param("age") Integer age);

	@Insert("insert into student(id,name,age) values(null,#{student.name},#{student.age})")
	@Result(jdbcType = JdbcType.INTEGER)
	@SelectKey(keyProperty = "student.id", keyColumn = "id", statement = "select @@identity as id", statementType = StatementType.STATEMENT, resultType = Integer.class, before = false)
	public int insert(@Param("student") Student student);

	@Delete("delete from student where id = #{student.id}")
	@Result(jdbcType = JdbcType.INTEGER)
	public int delete(@Param("student") Student student);

	//以下由工具自动生成,已自动生成配置信息
	int deleteByPrimaryKey(Integer id);

	int insertSelective(Student record);

	Student selectByPrimaryKey(Integer id);

	int updateByPrimaryKeySelective(Student record);

	int updateByPrimaryKey(Student record);
}

Mapper-StudentMapper.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.zjh.mapper.StudentMapper">
	<resultMap id="BaseResultMap" type="com.zjh.model.Student">
		<id column="id" property="id" jdbcType="INTEGER" />
		<result column="name" property="name" jdbcType="VARCHAR" />
		<result column="age" property="age" jdbcType="INTEGER" />
	</resultMap>
	<sql id="Base_Column_List">
		id, name, age
	</sql>
	<select id="selectByPrimaryKey" resultMap="BaseResultMap"
		parameterType="java.lang.Integer">
		select
		<include refid="Base_Column_List" />
		from student
		where id = #{id,jdbcType=INTEGER}
	</select>
	<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
		delete from student
		where id = #{id,jdbcType=INTEGER}
	</delete>
	<insert id="insert" parameterType="com.zjh.model.Student">
		insert into student (id, name, age
		)
		values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},
		#{age,jdbcType=INTEGER}
		)
	</insert>
	<insert id="insertSelective" parameterType="com.zjh.model.Student">
		insert into student
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="id != null">
				id,
			</if>
			<if test="name != null">
				name,
			</if>
			<if test="age != null">
				age,
			</if>
		</trim>
		<trim prefix="values (" suffix=")" suffixOverrides=",">
			<if test="id != null">
				#{id,jdbcType=INTEGER},
			</if>
			<if test="name != null">
				#{name,jdbcType=VARCHAR},
			</if>
			<if test="age != null">
				#{age,jdbcType=INTEGER},
			</if>
		</trim>
	</insert>
	<update id="updateByPrimaryKeySelective" parameterType="com.zjh.model.Student">
		update student
		<set>
			<if test="name != null">
				name = #{name,jdbcType=VARCHAR},
			</if>
			<if test="age != null">
				age = #{age,jdbcType=INTEGER},
			</if>
		</set>
		where id = #{id,jdbcType=INTEGER}
	</update>
	<update id="updateByPrimaryKey" parameterType="com.zjh.model.Student">
		update student
		set name = #{name,jdbcType=VARCHAR},
		age = #{age,jdbcType=INTEGER}
		where id = #{id,jdbcType=INTEGER}
	</update>
</mapper>

 

 

 

 

 

3.  配置mybatis需要的信息

在根目录下新建xml文件,取名为mybatis-config.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>
	<settings>
		<setting name="cacheEnabled" value="false" />
		<setting name="useGeneratedKeys" value="true" />
		<setting name="defaultExecutorType" value="REUSE" />
	</settings>

	<environments default="development">
		<environment id="development">
			<!-- 配置事务类型 -->
			<transactionManager type="jdbc" />
			<dataSource type="POOLED">
				<!--数据库驱动 -->
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<!-- 数据库URL -->
				<property name="url" value="jdbc:mysql://localhost:3306/mybatistest" />
				<!-- 数据库用户名 -->
				<property name="username" value="root" />
				<!-- 数据库密码 -->
				<property name="password" value="admin" />
			</dataSource>
		</environment>
	</environments>
	
 <mappers>
        <mapper resource="com/zjh/mapper/StudentMapper.xml"/>
    </mappers>
    
</configuration>

 

 

 

 

 

4. 测试

这里测试使用的是Junit

首先是获得Session

 

public SqlSession getSession() {
		//通过Resources读取mybatis配置文件
		try (Reader resource = Resources
				.getResourceAsReader("mybatis-config.xml")) {
			//根据配置文件建立SessioFactory
			SqlSessionFactory factory = new SqlSessionFactoryBuilder()
					.build(resource);
			//将StudentMapper在SessioFactory中注册
			factory.getConfiguration().addMapper(StudentMappper.class);
			//获取session
			return factory.openSession();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

下面依次做插入,删除,更新,查询的测试

 

 

@org.junit.Test
	public void insert() throws IOException {
		SqlSession session = getSession();

		Student student = new Student();
		student.setAge(21);
		student.setName("zjh63248");

		StudentMappper dao = session.getMapper(StudentMappper.class);
		System.out.println(dao.insert(student));
		session.commit();
		session.close();
		System.out.println(student.getId());
	}

	@org.junit.Test
	public void select() {
		SqlSession session = getSession();
		StudentMappper dao = session.getMapper(StudentMappper.class);

		List<Student> list = dao.findByName("zjh");
		for (Student s : list) {
			System.out.println(s.getName() + "的年龄是" + s.getAge());
		}
	}

	@org.junit.Test
	public void delete() {
		SqlSession session = getSession();
		StudentMappper dao = session.getMapper(StudentMappper.class);

		Student student = new Student();
		student.setAge(21);
		student.setName("zjh63248");
		student.setId(26);

		System.out.println(dao.delete(student));
		session.commit();
		session.close();
	}

	@org.junit.Test
	public void update() {
		SqlSession session = getSession();
		StudentMappper dao = session.getMapper(StudentMappper.class);

		Student student = new Student();
		student.setAge(21);
		student.setName("zjh");
		student.setId(27);

		System.out.println(dao.update(student));
		session.commit();
		session.close();
	}


到此结束,期间遇到的问题,会在下一章节做记录.

 

源码下载:http://download.csdn.net/detail/u013769320/8320717

 

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值