Mybatis自动生成器

Mybatis自动生成器

使用官方网站的Mapper自动生成工具mybatis-generator-core-1.3.7来生成po类和Mapper映射文件

pom.xml文件中添加generator插件

插件依赖信息

<plugin>
  <groupId>org.mybatis.generatorgroupId>
  <artifactId>mybatis-generator-maven-pluginartifactId>
  <version>1.3.7version>
  <executions>
    <execution>
      <id>Generate MyBatis Artifactsid>
      <goals>
        <goal>generategoal>
      goals>
    execution>
  executions>
  <dependencies>
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.45version>
    dependency>
  dependencies>
plugin>

添加加配置文件

在main\resources下在添加generatorConfig.xml中

配置如下:




<generatorConfiguration>
	<context id="testTables" targetRuntime="MyBatis3">
		<commentGenerator>
			
			<property name="suppressAllComments" value="true" />
		commentGenerator>
		
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/mybatis_01" userId="root"
			password="root">
		jdbcConnection>
		

		
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		javaTypeResolver>

		
		<javaModelGenerator targetPackage="包名.pojo"
			targetProject="src/main/java">
			
			<property name="enableSubPackages" value="false" />
			
			<property name="trimStrings" value="true" />
		javaModelGenerator>
        
		<sqlMapGenerator targetPackage="包名.mapper"
			targetProject="src/main/java">
			
			<property name="enableSubPackages" value="false" />
		sqlMapGenerator>
		
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="包名.mapper"
			targetProject="src/main/java">
			
			<property name="enableSubPackages" value="false" />
		javaClientGenerator>
		
		<table schema="" tableName="user" domainObjectName="MyUser">table>
		<table schema="" tableName="orders" domainObjectName="MyOrders">table>
		
		
	context>
generatorConfiguration>
  1. 修改要生成的数据库表
  2. pojo文件所在包路径
  3. Mapper所在的包路径

编写测试方法

public class UserMapperTest{
	@Test
	public void testInsert() {
      	SqlSession sqlSession = MyBatisUtils.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User();
		user.setUsername("刘德华");
		user.setSex("1");
		user.setBirthday(new Date());
		user.setAddress("香港");

		userMapper.insert(user);
	}

	@Test
	public void testSelectByExample() {
		SqlSession sqlSession = MyBatisUtils.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

		// 创建User对象扩展类,用户设置查询条件
		UserExample example = new UserExample();
		example.createCriteria().andUsernameLike("%刘%");

		// 查询数据
		List<User> list = userMapper.selectByExample(example);

		System.out.println(list.size());
	}

	@Test
	public void testSelectByPrimaryKey() {
		SqlSession sqlSession = MyBatisUtils.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = userMapper.selectByPrimaryKey(1);
		System.out.println(user);
	}
}

注意:

  1. 生成器生成的代码只能做单表查询
  2. 不能在生成的代码上进行扩展,因为如果数据库变更,需要重新使用逆向工程生成代码,原来编写的代码就被覆盖了。
  3. 一张表会生成4个文件

MyBatis的注解开发方式

从MyBatis3开始,注解提供了一种简单的方式来实现简单映射语句,这种方式不会引入大量的开销。但是灵活性较差,不易扩展。

Mybatis常用注解对应的目标和标签如表所示:

注解 目标 对应的XML标签
@Select 方法
@Insert 方法
@Update 方法
@Delete 方法
@Param 参数
@SelectKey 方法
@One 方法
@Many 方法

示例如下:


import org.apache.ibatis.annotations.*;

import java.util.List;
public interface UserMapper {
    @Select(value = "select * from user where id=#{id}")
    public User queryById(Integer id);
    @Select(value = "select * from user")
    public List<User> queryAll();
    @Insert(value = "insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address});")
    @SelectKey(keyProperty = "id",before = false,resultType = Integer.class,statement = "select LAST_INSERT_ID()")
    public void saveUser(User user);
    @Select(value = "select * from user where username like #{username} and sex=#{sex}")
    public List<User> findByWhere(@Param("username") String username, @Param("sex") String sex);
    @Update(value = "update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}")
    public void updateUser(User user);

}

你可能感兴趣的:(Mybatis自动生成器)