最初设计时,MyBatis 是一个 XML 驱动的框架。配置信息是基于 XML 的,而且映射语句也是定义在 XML 中的。随着技术的更新发展,对于开发效率要求也原来越高,特别是一些小型项目;越来越多的框架开始支持注解,
到MyBatis3时,MyBatis对注解有了完善的支持,利用注解可以在一些情况下提高开发效率
但不幸的是,Java 注解的的表达力和灵活性十分有限。尽管很多时间都花在调查、设计和试验上, 最强大的 MyBatis 映射并不能用注解来构建
接口方法声明:
import com.kkb.pojo.User; import org.apache.ibatis.annotations.Select; public interface UserMapper2 { @Select("select * from kuser where id = #{id}") public User selectUserByID(int id); }
测试方法:
@Test public void selectTest(){ SqlSession session = factory.openSession(); UserMapper2 mapper = session.getMapper(UserMapper2.class); User user = mapper.selectUserByID(2); System.out.println(user); session.close(); }
不要忘记注册这个接口到全局配置中
<mappers> <mapper class="com.kkb.mapper.UserMapper2"/> </mappers>
接口方法声明:
@Select("select * from kuser where sex = #{sex} and name like '%${name}%'") public List<User> selectUserBySexAndName(@Param("sex") String sex, @Param("name") String name);
测试方法:
@Test public void selectTest2(){ SqlSession session = factory.openSession(); UserMapper2 mapper = session.getMapper(UserMapper2.class); List<User> users = mapper.selectUserBySexAndName("1","张"); System.out.println(users); session.close(); }
一定要记住MyBatis的sql接受的参数只有一个无论实际传了几个
当sql语句需要多个参数时则必须将多个参数打包到一个对象中,通常是POJO或Map,上面的案例中使用了@Param注解本质就是告诉MyBatis有多个参数MyBatis或自动创建一个Map,然后将@Param的值作为Key,然后将Map传给sql,所以你也可以传一个手动传一个Map
接口方法声明:
@Select("select * from kuser where sex = #{sex} and name like '%${name}%'") public List<User> selectUserBySexAndName(Map<String,Object> params);
测试方法:
@Test public void selectTest2(){ SqlSession session = factory.openSession(); UserMapper2 mapper = session.getMapper(UserMapper2.class); Map<String,Object> params = new HashMap<>(); //存储参数的Map params.put("sex","1"); params.put("name","张"); List<User> users = mapper.selectUserBySexAndName(params); System.out.println(users); session.close(); }
接口方法声明:
@Insert("insert into kuser values(null,#{name},#{birthday},#{sex},#{address})") public int insertUser(User user);
测试方法:
@Test public void insertTest() { SqlSession session = factory.openSession(); UserMapper2 mapper = session.getMapper(UserMapper2.class); User user = new User(); user.setName("jerry"); user.setSex("1"); user.setAddress("亚洲中国"); user.setBirthday(new Date()); mapper.insertUser(user); session.commit(); session.close(); }
在@select注解的下方添加@selectKey注解来完成对自增主键的获取
@Insert("insert into kuser values(null,#{name},#{birthday},#{sex},#{address})") @SelectKey(statement = "select last_insert_id()",keyProperty = "id",resultType = Integer.class,before = false) public int insertUser(User user);
在执行insert之后执行last_insert_id()函数获取自增值,然后放入对象的某个属性中;
接口方法声明:
@Update("update kuser set name = #{name}, birthday = #{birthday}, sex = #{sex}, address = #{address} where id = #{id}") public int updateUser(User u); // 如果一行太长可以换行些 但是要注意sql语法
测试方法:
@Test public void updateTest() { SqlSession session = factory.openSession(); UserMapper2 mapper = session.getMapper(UserMapper2.class); User user = mapper.selectUserByID(1); user.setName("王六子"); mapper.updateUser(user); session.commit(); session.close(); }
接口方法声明:
@Delete("delete from kuser where id = #{id}") public int deleteUserByID(int id);
测试方法:
@Test public void deleteTest() { SqlSession session = factory.openSession(); UserMapper2 mapper = session.getMapper(UserMapper2.class); mapper.deleteUserByID(12); session.commit(); session.close(); }
动态sql值sql中包含逻辑代码,需要先运行逻辑代码最后产生sql语句,所以需要在注解中告诉MyBatis这是一个动态sql,通过 <script>sql....</script>
语法来指定;
若想要在sql中使用各种标签则必须添加上述根标签,否则MyBatis会将整体作为sql语句
接口方法声明:
@Select("<script>" + "select * from kuser" + "<where>" + "<if test='name != null'>" + "and name like '%${name}%'" + "</if>" + "<if test='sex != null'>" + "and sex = #{sex}" + "</if>" + "</where>" + "</script>") public List<User> searchUserByNameAndSex(@Param("name") String name,@Param("sex") String sex);
测试代码:
@Test public void dynamicSqlTest(){ SqlSession session = factory.openSession(); UserMapper2 mapper = session.getMapper(UserMapper2.class); List<User> users = mapper.searchUserByNameAndSex(null,null); // List<User> users = mapper.searchUserByNameAndSex("张",null); // List<User> users = mapper.searchUserByNameAndSex("张", "2"); System.out.println(users); session.close(); }
准备工作:将数据库中的name字段修改为username,然后我们通过ResultMap来手动映射name字段
接口方法声明:
@Select("select *from kuser where username = #{name}") @Results({ @Result(id = true,column = "id",property = "id"), @Result(column = "username",property = "name"), }) public User selectUserByName(String name);
测试代码省略..
可以发现,MyBatis默认会自动映射所有字段和属性匹配的数据,另外id表示是否为主键字段,默认为false
强调:Results可以位于对应方法的上面或下面,但是无法跨域其他方法,默认只对当前方法有效,如果需要重复使用则需要为其指定id
接口方法声明:
//定义 @Results(id="map1",value = { @Result(id = true,column = "id",property = "id"), @Result(column = "username",property = "name"), }) //.....中间必须间隔其他方法不能立即应用到某个ResultMap
使用:
@Select("select *from kuser where username = #{name}") //通过@ResultMap注解 并传入id来使用 @ResultMap("map1") public User selectUserByName(String name);
注意:@Results的定义不能不能和使用它的@ResultMap一起出现,既然是重复使用的那我建议统一接口的最上面
一对多关联
//实现根据用户姓名查询用户信息和订单信息 @Select("select *from kuser where username = #{name}") @Results(value = { @Result(id = true,column = "id",property = "id"), @Result(column = "username",property = "name"), //一对多关联,指定子查询语句的方法名称(全限定名称)column指定传给子查询的参数 @Result(column = "id",property = "orders",many = @Many(select = "com.kkb.mapper.UserMapper2.selectOrdersByID")), }) public User selectUserAdnOrdersByUserName(String name); //注意这里的条件字段时order表中的字段 @Select("select *from Orders where user_id = #{id}") public List<Order> selectOrdersByID(int id);
一对一关联 只需要修改属性名称和注解名称即可:
@Select("select *from orders where id = #{id}") @Results(value = { @Result(id = true,column = "id",property = "id"), @Result(column = "user_id",property = "user" ,one = @One(select = "com.kkb.mapper.UserMapper2.selectUserByID")), }) public Order selectOrderByID(int id);
generator翻译为生成器,是MyBatis开源的一个插件,可以从数据库获取表信息,自动生成 Mapper.xml
, POJO
,以及 Mapper
接口
但问题是,MyBatis不可能完全清楚我们的业务需求,所以其自动生成的sql只能满足基本的CRUD操作,而无法帮助我们进行连表操作,(当然包括带有条件的CRUD)
<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <!-- 是否覆盖已存在的接口和POJO--> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build>
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--导入属性配置--> <properties resource="jdbc.properties"></properties> <!--指定特定数据库的jdbc驱动jar包的位置--> <classPathEntry location="${location}"/> <context id="default" targetRuntime="MyBatis3"> <!-- optional,旨在创建class时,对注释进行控制 --> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--jdbc的数据库连接 --> <jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${user}" password="${password}"> </jdbcConnection> <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制--> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!--Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类 targetPackage 指定生成的model生成所在的包名 targetProject 指定在该项目下所在的路径 --> <javaModelGenerator targetPackage="com.kaikeba.pojo" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> <!-- 是否对model添加 构造函数 --> <property name="constructorBased" value="true"/> <!-- 是否对类CHAR类型的列的数据进行trim操作 --> <property name="trimStrings" value="true"/> <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> <property name="immutable" value="false"/> </javaModelGenerator> <!--mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 --> <sqlMapGenerator targetPackage="com.kaikeba.dao" targetProject="src/main/resources"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!--mapper接口文件生成所在的目录 为每一个数据库的表生成对应的接口文件 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.kaikeba.dao" targetProject="src/main/java"> <!-- enableSubPackages:是否让schema(数据库名称)作为包的后缀 --> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!--指定需要生成的表--> <table tableName="category"></table> <table tableName="orders"></table> <table tableName="products"></table> <table tableName="kuser"></table> </context> </generatorConfiguration>
上述配置是一个较为通用的配置,实际开发中要根据需求进行修改
若自定义配置文件名称则需要在pom中指定
<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <!-- 自定义配置文件 相对于项目根目录--> <configurationFile>src/main/resources/aaaa.xml</configurationFile> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build>
可在idea右侧的maven菜单中双击执行mybatis-generator:generate
也可利用maven命令执行: mybatis-generator:generate
generator的目标是尽可能的帮我们减少sql的编写,如果只能进行简单的CRUD那意义不大,于是generator使用了一套Example来帮助我们用OOP(面向对象)的方式来完成SQL中的条件拼接
其设计思想是将条件看做是一个对象,该对象包含了SQL中常见的比较,逻辑运算等......打开文件你会发现其本质就是帮我们拼接响应的sql符号和关键字
import com.kaikeba.dao.KuserMapper; import com.kaikeba.pojo.Kuser; import com.kaikeba.pojo.KuserExample; 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 java.io.IOException; import java.io.InputStream; import java.util.List; public class GeneratorTest { private SqlSessionFactory factory; @Before public void init() throws IOException { //获取的工厂构造器 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //加载配置文件 InputStream stream = Resources.getResourceAsStream("mybatis-config.xml"); //获得会话工厂 factory = builder.build(stream); } //查询 @Test public void test(){ SqlSession session = factory.openSession(); KuserMapper mapper = session.getMapper(KuserMapper.class); Kuser kuser = mapper.selectByPrimaryKey(1); System.out.println(kuser.getSex()); System.out.println(kuser.getAddress()); System.out.println(kuser.getBirthday()); System.out.println(kuser.getUsername()); } //修改 @Test public void test2(){ SqlSession session = factory.openSession(); KuserMapper mapper = session.getMapper(KuserMapper.class); Kuser kuser = mapper.selectByPrimaryKey(1); kuser.setUsername("XXXXXXXXX"); mapper.updateByPrimaryKey(kuser); session.commit(); } //添加 @Test public void test3(){ SqlSession session = factory.openSession(); KuserMapper mapper = session.getMapper(KuserMapper.class); Kuser auser = new Kuser(); auser.setUsername("jack"); auser.setAddress("北京东城"); mapper.insert(auser); session.commit(); } //删除 @Test public void test4() { SqlSession session = factory.openSession(); KuserMapper mapper = session.getMapper(KuserMapper.class); mapper.deleteByPrimaryKey(13); session.commit(); } //and条件 @Test public void test5() { SqlSession session = factory.openSession(); KuserMapper mapper = session.getMapper(KuserMapper.class); KuserExample kuserExample = new KuserExample(); KuserExample.Criteria criteria = kuserExample.createCriteria(); criteria.andBirthdayIsNotNull(); criteria.andUsernameLike("%张%"); List<Kuser> kusers = mapper.selectByExample(kuserExample); System.out.println(kusers); } // or条件 @Test public void test6() { SqlSession session = factory.openSession(); KuserMapper mapper = session.getMapper(KuserMapper.class); KuserExample kuserExample = new KuserExample(); //创建一个条件对象,可以包含n个and KuserExample.Criteria criteria1 = kuserExample.createCriteria(); criteria1.andUsernameLike("%张%"); //创建一个条件对象可以包含n个and,且前面添加or关键字 KuserExample.Criteria criteria2 = kuserExample.or(); criteria2.andBirthdayIsNull(); //最终的意思是 名字带有张的 或者生日为空的; 具体逻辑可根据生产的sql进行分析 List<Kuser> kusers = mapper.selectByExample(kuserExample); System.out.println(kusers); } }