05_MyBatis基于注解的开发

简介:  要想开发基于注解的MyBatis应用。需要先写一个带有注解的接口。 PersonDao.java的写法如下: package com.rl.dao;   import java.util.List; import java.util.Map;   import org.apache.ibatis.anno

  1. 要想开发基于注解的MyBatis应用。需要先写一个带有注解的接口。

PersonDao.java的写法如下:

package com.rl.dao;

 

import java.util.List;

import java.util.Map;

 

import org.apache.ibatis.annotations.Delete;

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Result;

import org.apache.ibatis.annotations.ResultMap;

import org.apache.ibatis.annotations.Results;

import org.apache.ibatis.annotations.Select;

import org.apache.ibatis.annotations.SelectKey;

import org.apache.ibatis.annotations.SelectProvider;

import org.apache.ibatis.annotations.Update;

 

import com.rl.model1.Person;

import com.rl.util.SqlHelper;

 

public interface PersonDao {

        

         @Select("select * from person t where t.person_id = #{personId}")

         @Results(value={

                   @Result(column="person_id", property="personId", id=true),

                   @Result(column="name", property="name"),

                   @Result(column="gender", property="gender"),

                   @Result(column="person_addr", property="personAddr"),

                   @Result(column="birthday", property="birthday")

         })

         public Person selectPersonById(Integer personId);

        

         @Select("select * from person")

         @Results(value={

                   @Result(column="person_id", property="personId", id=true),

                   @Result(column="name", property="name"),

                   @Result(column="gender", property="gender"),

                   @Result(column="person_addr", property="personAddr"),

                   @Result(column="birthday", property="birthday")

         })

         public List<Person> selectPersonAll();

        

         @Select("select * from person t where t.gender = #{gender} and t.birthday < #{birthday}")

         @Results(value={

                   @Result(column="person_id", property="personId", id=true),

                   @Result(column="name", property="name"),

                   @Result(column="gender", property="gender"),

                   @Result(column="person_addr", property="personAddr"),

                   @Result(column="birthday", property="birthday")

         })

         public List<Person> selectPersonByParams(Map<String,Object> map);

        

        

         @Select("select * from person t where t.name like '%${name}%'")

         @Results(value={

                            @Result(column="person_id", property="personId", id=true),

                            @Result(column="name", property="name"),

                            @Result(column="gender", property="gender"),

                            @Result(column="person_addr", property="personAddr"),

                            @Result(column="birthday", property="birthday")

         })

         public List<Person> selectPersonByLike(Map<String,Object> map);

        

 

         @Insert("insert into person (person_id, name, gender, person_addr, birthday) " +

                            "values(#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday})")

         @SelectKey(before = false, keyProperty = "personId", resultType = java.lang.Integer.class, statement = { "select LAST_INSERT_ID()" })

         public void insert(Person person);

        

         @Update("update person p set p.name = #{name}," +

                            "p.gender = #{gender}," +

                            "p.person_addr = #{personAddr}," +

                            "p.birthday = #{birthday} " +

                            "where p.person_id = #{personId}")

         public void update(Person person);

        

         @Delete("delete from person where person_id = #{personId}")

         public void delete(Integer personId);

        

         @SelectProvider(type=SqlHelper.class, method="getSql")

         @Results(value={

                            @Result(column="person_id", property="personId", id=true),

                            @Result(column="name", property="name"),

                            @Result(column="gender", property="gender"),

                            @Result(column="person_addr", property="personAddr"),

                            @Result(column="birthday", property="birthday")

         })

         public List<Person> selectPersonByCondition(Map<String,Object> map);

        

         @Select("select * from person p, orders o where p.person_id = o.person_id and p.person_id = #{personId}")

         @ResultMap(value="com.rl.mapper.PersonMapper.selectPersonAndOrderByPIdRM")

         public Person selectOrdersByPersonId(Integer personId);

}

测试类:

package com.rl.test;

 

import java.io.InputStream;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

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 com.rl.dao.PersonDao;

import com.rl.model1.Person;

 

/**

 * mybatis的注解开发

 */

public class MybatisTest6 {

 

         SqlSessionFactory sessionFactory;

        

         @Before

         public void setUp() throws Exception {

                   InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");

                   sessionFactory = new SqlSessionFactoryBuilder().build(in);

                   //注册接口

                   sessionFactory.getConfiguration().addMapper(PersonDao.class);

         }

 

         @Test

         public void selectPersonById(){

                   SqlSession session = sessionFactory.openSession();

                   //获得接口的实现类

                   PersonDao personDao = session.getMapper(PersonDao.class);

                   try {

                            Person person = personDao.selectPersonById(1);

                            System.out.println(person);

                   }finally{

                            session.close();

                   }

         }

        

         @Test

         public void selectPersonAll(){

                   SqlSession session = sessionFactory.openSession();

                   //获得接口的实现类

                   PersonDao personDao = session.getMapper(PersonDao.class);

                   try {

                            List<Person> pList = personDao.selectPersonAll();

                            for(Person p : pList){

                                     System.out.println(p);

                            }

                   } finally {

                            session.close();

                   }

         }

        

         @Test

         public void selectPersonByParams() throws Exception {

                   SqlSession session = sessionFactory.openSession();

                   //获得接口的实现类

                   PersonDao personDao = session.getMapper(PersonDao.class);

                   Map<String,Object> map = new HashMap<String,Object>();

                   map.put("gender", 0);

                   map.put("birthday", new SimpleDateFormat("yyyy-MM-dd").parse("2014-08-08"));

                   try {

                            List<Person> pList = personDao.selectPersonByParams(map);

                            for(Person p : pList){

                                     System.out.println(p);

                            }

                   } finally {

                            session.close();

                   }

         }

        

         @Test

         public void selectPersonByLike() throws Exception{

                   SqlSession session = sessionFactory.openSession();

                   //获得接口的实现类

                   PersonDao personDao = session.getMapper(PersonDao.class);

                   Map<String,Object> map = new HashMap<String,Object>();

                   map.put("name", "");

                   try {

                            List<Person> pList = personDao.selectPersonByLike(map);

                            for(Person p : pList){

                                     System.out.println(p);

                            }                          

                   }finally{

                            session.close();

                   }

         }

        

         @Test

         public void insert() throws Exception{

                   SqlSession session = sessionFactory.openSession();

                   //获得接口的实现类

                   PersonDao personDao = session.getMapper(PersonDao.class);

                   try {

                            Person p = new Person();

                            p.setName("西门庆");

                            p.setGender("0");

                            p.setPersonAddr("阳谷县");

                            p.setBirthday(new Date());

                            personDao.insert(p);

                            session.commit();

                   }catch(Exception ex){

                            ex.printStackTrace();

                            session.rollback();

                   }finally{

                            session.close();

                   }

         }

        

         @Test

         public void update() throws Exception{

                   SqlSession session = sessionFactory.openSession();

                   //获得接口的实现类

                   PersonDao personDao = session.getMapper(PersonDao.class);

                   try {

                            Person p = new Person();

                            p.setPersonId(5);

                            p.setName("大官人");

                            p.setGender("0");

                            p.setPersonAddr("阳谷县");

                            p.setBirthday(new Date());

                            personDao.update(p);

                            session.commit();

                   }catch(Exception ex){

                            ex.printStackTrace();

                            session.rollback();

                   }finally{

                            session.close();

                   }

         }

        

         @Test

         public void delete() throws Exception{

                   SqlSession session = sessionFactory.openSession();

                   //获得接口的实现类

                   PersonDao personDao = session.getMapper(PersonDao.class);

                   try {

                            personDao.delete(5);

                            session.commit();

                   }catch(Exception ex){

                            ex.printStackTrace();

                            session.rollback();

                   }finally{

                            session.close();

                   }

         }

        

         /**

          * 动态条件组合查询

          */

         @Test

         public void selectPersonByCondition() throws Exception{

                   SqlSession session = sessionFactory.openSession();

                   //获得接口的实现类

                   PersonDao personDao = session.getMapper(PersonDao.class);

                   Map<String,Object> map = new HashMap<String,Object>();

                   //map.put("name", "");

                   //map.put("gender", "0");

                   //map.put("personAddr", "");

                   //map.put("birthday", new Date());

                   try {

                            List<Person> pList = personDao.selectPersonByCondition(map);

                            for(Person p : pList){

                                     System.out.println(p);

                            }

                   } finally {

                            session.close();

                   }

         }

         /**

          * 管理查询

          */

         @Test

         public void selectOrdersByPersonId() throws Exception{

                   SqlSession session = sessionFactory.openSession();

                   //获得接口的实现类

                   PersonDao personDao = session.getMapper(PersonDao.class);

                   try {

                            Person person = personDao.selectOrdersByPersonId(1);

                            System.out.println(person);

                   }finally{

                            session.close();

                   }

         }

}

 

目录
相关文章
|
29天前
|
SQL Java 数据库连接
【MyBatisPlus·最新教程】包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段
MyBatis-Plus是一个MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。本文讲解了最新版MP的使用教程,包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段等核心功能。
【MyBatisPlus·最新教程】包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段
|
1月前
|
SQL 缓存 Java
MyBatis如何关闭一级缓存(分注解和xml两种方式)
MyBatis如何关闭一级缓存(分注解和xml两种方式)
69 5
|
1月前
|
Java 数据库连接 mybatis
Mybatis使用注解方式实现批量更新、批量新增
Mybatis使用注解方式实现批量更新、批量新增
51 3
|
1月前
|
SQL 存储 数据库
深入理解@TableField注解的使用-MybatisPlus教程
`@TableField`注解在MyBatis-Plus中是一个非常灵活和强大的工具,能够帮助开发者精细控制实体类与数据库表字段之间的映射关系。通过合理使用 `@TableField`注解,可以实现字段名称映射、自动填充、条件查询以及自定义类型处理等高级功能。这些功能在实际开发中,可以显著提高代码的可读性和维护性。如果需要进一步优化和管理你的MyBatis-Plus应用程
161 3
|
1月前
|
Java 数据库连接 mybatis
Mybatis使用注解方式实现批量更新、批量新增
Mybatis使用注解方式实现批量更新、批量新增
73 1
|
3月前
|
SQL XML Java
mybatis复习02,简单的增删改查,@Param注解多个参数,resultType与resultMap的区别,#{}预编译参数
文章介绍了MyBatis的简单增删改查操作,包括创建数据表、实体类、配置文件、Mapper接口及其XML文件,并解释了`#{}`预编译参数和`@Param`注解的使用。同时,还涵盖了resultType与resultMap的区别,并提供了完整的代码实例和测试用例。
mybatis复习02,简单的增删改查,@Param注解多个参数,resultType与resultMap的区别,#{}预编译参数
|
2月前
|
前端开发 Java 数据库连接
表白墙/留言墙 —— 中级SpringBoot项目,MyBatis技术栈MySQL数据库开发,练手项目前后端开发(带完整源码) 全方位全步骤手把手教学
本文是一份全面的表白墙/留言墙项目教程,使用SpringBoot + MyBatis技术栈和MySQL数据库开发,涵盖了项目前后端开发、数据库配置、代码实现和运行的详细步骤。
67 0
表白墙/留言墙 —— 中级SpringBoot项目,MyBatis技术栈MySQL数据库开发,练手项目前后端开发(带完整源码) 全方位全步骤手把手教学
|
3月前
|
Java 数据库连接 数据格式
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
IOC/DI配置管理DruidDataSource和properties、核心容器的创建、获取bean的方式、spring注解开发、注解开发管理第三方bean、Spring整合Mybatis和Junit
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
|
4月前
|
SQL Java 数据库
5、Mybatis-Plus 常用注解
这篇文章详细介绍了Mybatis-Plus中常用的注解,包括解决实体类与数据库表名不一致、字段不匹配的问题,主键生成策略的配置,以及逻辑删除的实现方法。
5、Mybatis-Plus 常用注解
|
4月前
|
SQL Java 数据库连接
Spring Boot联手MyBatis,打造开发利器:从入门到精通,实战教程带你飞越编程高峰!
【8月更文挑战第29天】Spring Boot与MyBatis分别是Java快速开发和持久层框架的优秀代表。本文通过整合Spring Boot与MyBatis,展示了如何在项目中添加相关依赖、配置数据源及MyBatis,并通过实战示例介绍了实体类、Mapper接口及Controller的创建过程。通过本文,你将学会如何利用这两款工具提高开发效率,实现数据的增删查改等复杂操作,为实际项目开发提供有力支持。
260 0