MyBatis使用注解开发以及动态SQL

1、使用注解进行开发的CRUD

  • 使用注解开发就是在接口的方法上面添加注解语句,从而实现代替xml文件的作用
1.1、select
public interface UserMapper {
	@Select("select * from `user`")
	List<User> getUserList();
}
  • 进行测试
public void getUserList(){
		SqlSession sqlSession = MyBatisUtil.getSqlSession();
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		List<User> list = mapper.getUserList();
		for (User user : list) {
			System.out.println(user);
		}
	}
1.2、insert
@Insert("insert into `user`(id,name,pwd) values(#{id},#{name},#{pwd})")
	int addUser(User user);
  • 测试
public void addUser(){
		//进行增删改,要开启事务
		SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		int i = mapper.addUser(new User(1, "小黄", "111111"));
		if (i >= 1){
			System.out.println("新增成功");
		}
	}
1.3、delete
//删除用户信息
	@Delete("delete from user where id=#{id}")
	int deleteUser(int id);
  • 测试
public void deleteUser(){
		//进行增删改,要开启事务
		SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		int i = mapper.deleteUser(1);
		if (i >= 1){
			System.out.println("删除成功");
		}
	}
1.4、update
//修改用户信息
	@Update("update user set name = #{name},pwd = #{pwd} where id = #{id}")
	int updateUser(User user);
  • 测试
public void updateUser(){
		//进行增删改,要开启事务
		SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		int i = mapper.updateUser(new User(2, "老牛", "333333"));
		if (i >= 1){
			System.out.println("修改成功");
		}
	}
  • 或者使用万能的map来传递参数
//修改用户信息
	@Update("update user set name = #{name},pwd = #{pwd} where id = #{id}")
	int updateUser(HashMap<String,Object> map);
  • 测试
public void updateUser(){
		//进行增删改,要开启事务
		SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("id",2);
		map.put("name","小牛");
		map.put("pwd",233333);
		int i = mapper.updateUser(map);
		if (i >= 1){
			System.out.println("修改成功");
		}
	}

2、多对一以及一对多的处理

  • 现在分别创建一个student表和teacher表,其中student表中的tid字段与teacher表中的id字段相对应
CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师'); 

CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8


INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
2.1、获取所有学生以及学生对应老师的信息
  • 创建student和teacher的实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
	private int id;
	private String name;
	//要通过teacher对象查出对应的tid
	private Teacher teacher;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
	private int id;
	private String name;
}
  • 创建接口方法
public interface StudentMapper {
	List<Student> getStudent();
}
  • 书写xml语句
<resultMap id="StudentTeacher" type="org.westos.pojo.Student">
        <!--property对应属性名,column对应数据库表中的字段名-->
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <!--要用teacher对象去关联teacher表中的tid-->
        <association property="teacher" javaType="org.westos.pojo.Teacher">
            <result property="id" column="tid"/>
            <result property="name" column="tname"/>
        </association>
    </resultMap>
    <select id="getStudent" resultMap="StudentTeacher">
    <!--将列名设置为sid,sname,tid,tname-->
        select s.id as sid,s.name as sname,t.id as tid,t.name as tname
        from student as s,teacher as t
        where s.tid=t.id
    </select>
  • 测试
public void test1(){
		SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
		StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
		List<Student> list = mapper.getStudent();
		for (Student student : list) {
			System.out.println(student);
		}
	}
2.2、获取所有老以及对应学生的信息
  • 创建student和teacher的实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
	private int id;
	private String name;
//	//要查出对应老师的信息
//	private Teacher teacher;
	private int tid;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
	private int id;
	private String name;
	//老师对应的学生是多个的,所以用集合存储
	private List<Student> students;
}
  • 创建接口方法
public interface TeacherMapper {
	Teacher getTeacher(int id);
}
  • 书写xml语句
<resultMap id="TeacherStudent" type="org.westos.pojo.Teacher">
        <id property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="org.westos.pojo.Student">
            <id property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id as sid,s.name as sname,t.id as tid,t.name as tname
        from student as s,teacher as t 
        where s.tid=t.id and t.id=#{id}
    </select>
  • 测试
public void test2(){
		SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
		TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
		Teacher teacher = mapper.getTeacher(1);
		System.out.println(teacher);

	}

3、动态SQL

  • 动态SQL就是指根据不同的参数生成不同的SQL语句
  • 创建一个sql数据库表
CREATE TABLE `blog` (
  `id` varchar(50) NOT NULL COMMENT '博客id',
  `title` varchar(100) NOT NULL COMMENT '博客标题',
  `author` varchar(30) NOT NULL COMMENT '博客作者',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8

  • 创建对应的实体类
@Data
public class Blog {
	private int id;
	private String title;
	private String author;
	private Date createTime;
	private int views;
}
  • 在mybatis-config.xml文件中添加mapUnderscoreToCamelCase的setting属性,并设置为true,可以实现驼峰命名和数据库名的自动转换
<settings>
        <setting name="logImpl" value="LOG4J"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
3.1、if语句
  • if语句的格式为 执行语句,如果有两个if语句,那么就可以进行适配的工作了,比如满足第一个if则执行第一个,满足第二个则执行第二个
  • 接口
public interface BlogMapper {
	List<Blog> getBlogIf(Map map);
}
  • 书写xml语句
<select id="getBlogIf" resultType="org.westos.pojo.Blog">

      select * from mybatis.blog
      <where>
          <if test="title!=null">
              title=#{title}
          </if>
          <if test="author!=null">
              and author=#{author}
          </if>
      </where>
    </select>
  • 测试,当只输入title和author时,都可以查询出信息,如果二者都不输入,那么也不会报错,因为where标签会识别信息,如果没识别到就不会进入where标签
	public void test1(){
		BlogMapper mapper = MyBatisUtil.getSqlSession().getMapper(BlogMapper.class);
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("title","mybatis");
		map.put("author","henry");
		List<Blog> blogIf = mapper.getBlogIf(map);
		for (Blog blog : blogIf) {
			System.out.println(blog);
		}
	}
3.2、choose、when、otherwise语句
  • choose语句类似于java中的switch case
  • 接口
List<Blog> queryBlog(Map map);
  • xml语句
<select id="queryBlog" parameterType="map" resultType="Blog">
        select * from mybatis.blog
        <where>
            <choose>
                <when test="title!=null">
                    title=#{title}
                </when>
                <when test="author!=null">
                    and author=#{author}
                </when>
                <otherwise>
                    and views=#{views}
                </otherwise>
            </choose>
        </where>
    </select>
  • 测试
public void test4(){
		BlogMapper mapper = MyBatisUtil.getSqlSession(true).getMapper(BlogMapper.class);
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("author","MyBoy");
		List<Blog> blogs = mapper.queryBlog(map);
		for (Blog blog : blogs) {
			System.out.println(blog);
		}
	}
3.3、set语句
  • 如果用户想更改表中的数据,但是我们又不知道用户具体会更改哪几个数据,所以update语句中的set应该是随着用户的输入发生变化的,这就是set语句的作用
  • 接口
int updateBlog(Map map);
  • xml语句
<update id="updateBlog" parameterType="map">
      update mybatis.blog
      <set>
          <if test="title!=null">
              title=#{title},
          </if>
          <if test="author!=null">
              author=#{author}
          </if>
      </set>
        where id=#{id}
    </update>
  • 测试,只输入了author的信息,也成功修改了
public void test3(){
		BlogMapper mapper = MyBatisUtil.getSqlSession(true).getMapper(BlogMapper.class);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("author","MyBoy");
		map.put("id",1);
		int i = mapper.updateBlog(map);
		if (i > 0){
			System.out.println("修改成功");
		}
	}
3.4、Foreach语句
  • 接口
List<Blog> queryBlogByForeach(Map map);
  • xml语句,item就是将collection中的元素进行遍历,open和close表示将遍历出的元素放在一个什么情境中,该例子中为(),separator表示每个元素之间用什么连接
<select id="queryBlogByForeach" resultType="Blog">
        select * from mybatis.blog
        <where>
            <foreach collection="ids" item="id" open="(" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>
  • 测试
public void test5(){
		BlogMapper mapper = MyBatisUtil.getSqlSession(true).getMapper(BlogMapper.class);
		HashMap<String, ArrayList> map = new HashMap<String, ArrayList>();
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(3);
		map.put("ids",list);
		List<Blog> blogs = mapper.queryBlogByForeach(map);
		for (Blog blog : blogs) {
			System.out.println(blog);
		}
	}
3.5、动态SQL总结
  • if语句用来做条件判断,当if语句都不满足时,sql语句就错误了,所以使用where语句,会自动识别,如果没有符合条件的,就不会执行。
  • set语句,当使用update时,很大的概率下我们并不知道用户会修改几个信息,那么我们就想着创造一个可以随用户输入的信息个数随时变化的语句,这就是set的功能,他配合if语句,可以实现相关的操作。
  • foreach语句,当我们查询使用例如where in(a or b or c)这种语句时,我们并不能确定用户到底回输入几个元素,因此需要将用户若输入的信息放在集合中,然后在拿到集合后将元素再单独遍历出来,最后进行判断。foreach要配合item(每个元素),open(以什么开始),close(以什么结束),separator(元素之间用什么连接)来使用。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值