菜单

mybatis逆向工程的部署,mybatis逆向工程

2018年11月16日 - Java

前不久当类型被行使至springboot与mybatis,在进展整并过程遭到遇到有的坑,在此将其整理出来,便于以后翻看与习。
型周转条件呢:eclispe+jdk1.8+maven

mybatis逆向工程的配备,mybatis逆向工程

逆向工程

1.哟是逆向工程

mybaits需要程序员自己编写sql语句,mybatis官方提供逆向工程
可以针对单表自动生成mybatis执行所要之代码(mapper.java,mapper.xml、po..)

公司实际开支中,常用之逆向工程方:
鉴于数据库的表生成java代码。

2.下充斥逆向工程
mybatis-generator-core-1.3.2-bundle.zip

3.采取办法(会用)

3.1运作逆向工程 
官方文档中提供的运转逆向工程的几乎栽办法
Running MyBatis Generator

MyBatis Generator (MBG) can be run in the following ways:

(1)From the command prompt with an XML configuration
(2)As an Ant task with an XML configuration
(3)As a Maven Plugin
(4)From another Java program with an XML configuration
(5)From another Java program with a Java based configuration
(6)还好透过eclipse的插件生成代码

建议下java程序方法(From another Java program with an XML
configuration),不依赖开发工具。

脚创建一个生成逆向文件的工程,将自动生成的文书还拷贝到原工程被去(这么做是以放止直接在来文件中生成会覆盖掉同名文件)
导入的jar包和工程组织截图如下:

如图

图片 1

3.2要命成代码配置文件
generatorConfig.xml:

[html] view plain copy  

  1. <?xml version=”1.0″ encoding=”UTF-8″?>  
  2. <!DOCTYPE generatorConfiguration  
  3.   PUBLIC “-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN”  
  4.   “http://mybatis.org/dtd/mybatis-generator-config\_1\_0.dtd"&gt;  
  5.   
  6. <generatorConfiguration>  
  7.     <context id=”testTables” targetRuntime=”MyBatis3″>  
  8.         <commentGenerator>  
  9.             <!– 是否去自动生成的诠释 true:是 : false:否 –>  
  10.             <property name=”suppressAllComments” value=”true” />  
  11.         </commentGenerator>  
  12.         <!–数据库连接的音:驱动类、连接地址、用户称、密码 –>  
  13.         <jdbcConnection driverClass=”com.mysql.jdbc.Driver”  
  14.             connectionURL=”jdbc:mysql://localhost:3306/mybatis” userId=”root”  
  15.             password=”1234″>  
  16.         </jdbcConnection>  
  17.         <!– <jdbcConnection driverClass=”oracle.jdbc.OracleDriver”  
  18.             connectionURL=”jdbc:oracle:thin:@127.0.0.1:1521:yycg”   
  19.             userId=”yycg”  
  20.             password=”yycg”>  
  21.         </jdbcConnection> –>  
  22.   
  23.         <!– 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和   
  24.             NUMERIC 类型解析为java.math.BigDecimal –>  
  25.         <javaTypeResolver>  
  26.             <property name=”forceBigDecimals” value=”false” />  
  27.         </javaTypeResolver>  
  28.   
  29.         <!– targetProject:生成PO类的职 –>  
  30.         <javaModelGenerator targetPackage=”cn.edu.hpu.ssm.po”  
  31.             targetProject=”.\src”>  
  32.             <!– enableSubPackages:是否给schema作为保的后缀 –>  
  33.             <property name=”enableSubPackages” value=”false” />  
  34.             <!– 于数据库返回的价为清理内外的空格 –>  
  35.             <property name=”trimStrings” value=”true” />  
  36.         </javaModelGenerator>  
  37.         <!– targetProject:mapper映射文件生成的岗位 –>  
  38.         <sqlMapGenerator targetPackage=”cn.edu.hpu.ssm.mapper”   
  39.             targetProject=”.\src”>  
  40.             <!– enableSubPackages:是否受schema作为担保的后缀 –>  
  41.             <property name=”enableSubPackages” value=”false” />  
  42.         </sqlMapGenerator>  
  43.         <!– targetPackage:mapper接口生成的职 –>  
  44.         <javaClientGenerator type=”XMLMAPPER”  
  45.             targetPackage=”cn.edu.hpu.ssm.mapper”   
  46.             targetProject=”.\src”>  
  47.             <!– enableSubPackages:是否给schema作为确保的后缀 –>  
  48.             <property name=”enableSubPackages” value=”false” />  
  49.         </javaClientGenerator>  
  50.         <!– 指定数据库表 –>  
  51.         <table tableName=”items”></table>  
  52.         <table tableName=”orders”></table>  
  53.         <table tableName=”orderdetail”></table>  
  54.         <table tableName=”user”></table>  
  55.         <!– <table schema=”” tableName=”sys_user”></table>  
  56.         <table schema=”” tableName=”sys_role”></table>  
  57.         <table schema=”” tableName=”sys_permission”></table>  
  58.         <table schema=”” tableName=”sys_user_role”></table>  
  59.         <table schema=”” tableName=”sys_role_permission”></table> –>  
  60.           
  61.         <!– 有些表的字段需要指定java类型  
  62.          <table schema=”” tableName=””>  
  63.             <columnOverride column=”” javaType=”” />  
  64.         </table> –>  
  65.     </context>  
  66. </generatorConfiguration>  

3.3执生成程序
GeneratorSqlmap.java: 

[java] view plain copy  

  1. import java.io.File;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4.   
  5. import org.mybatis.generator.api.MyBatisGenerator;  
  6. import org.mybatis.generator.config.Configuration;  
  7. import org.mybatis.generator.config.xml.ConfigurationParser;  
  8. import org.mybatis.generator.internal.DefaultShellCallback;  
  9.   
  10.   
  11. public class GeneratorSqlmap {  
  12.   
  13.   
  14.     public void generator() throws Exception{  
  15.   
  16.   
  17.         List<String> warnings = new ArrayList<String>();  
  18.         boolean overwrite = true;  
  19.         //加载配置文件  
  20.         File configFile = new File(“generatorConfig.xml”);   
  21.         ConfigurationParser cp = new ConfigurationParser(warnings);  
  22.         Configuration config = cp.parseConfiguration(configFile);  
  23.         DefaultShellCallback callback = new DefaultShellCallback(overwrite);  
  24.         MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,  
  25.                 callback, warnings);  
  26.         myBatisGenerator.generate(null);  
  27.   
  28.   
  29.     }   
  30.     public static void main(String[] args) throws Exception {  
  31.         try {  
  32.             GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();  
  33.             generatorSqlmap.generator();  
  34.         } catch (Exception e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.           
  38.     }  
  39. }  

浮动后底代码:

如图

图片 2

3.4使用生成的代码

要将转移工程中所大成的代码拷贝到自己之工中。我们这里吧ItemsMapper.java和ItemsMapper.xml、Items、ItemsExample类拷入我们的原来工程。

测试ItemsMapper中的法

[java] view plain copy  

  1. package cn.edu.hpu.ssm.test;  
  2.   
  3. import static org.junit.Assert.fail;  
  4.   
  5. import java.util.Date;  
  6. import java.util.List;  
  7.   
  8.   
  9. import org.junit.Before;  
  10. import org.junit.Test;  
  11. import org.springframework.context.ApplicationContext;  
  12. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  13.   
  14.   
  15. import cn.edu.hpu.ssm.mapper.ItemsMapper;  
  16. import cn.edu.hpu.ssm.po.Items;  
  17. import cn.edu.hpu.ssm.po.ItemsExample;  
  18.   
  19.   
  20. public class ItemsMapperTest {  
  21.   
  22.   
  23.     private ApplicationContext applicationContext;  
  24.       
  25.     private ItemsMapper itemsMapper;  
  26.       
  27.     //注解Before是当履本类所有测试方法之前先行调用这个办法  
  28.     @Before  
  29.     public void setup() throws Exception{  
  30.         applicationContext=new ClassPathXmlApplicationContext(“classpath:spring/applicationContext.xml”);  
  31.         itemsMapper=(ItemsMapper)applicationContext.getBean(“itemsMapper”);  
  32.     }  
  33.       
  34.     //根据主键删除  
  35.     @Test  
  36.     public void testDeleteByPrimaryKey() {  
  37.         fail(“Not yet implemented”);  
  38.     }  
  39.   
  40.   
  41.     //插入  
  42.     @Test  
  43.     public void testInsert() {  
  44.         Items items=new Items();  
  45.         items.setName(“iPhone-5S”);  
  46.         items.setPrice(3999f);  
  47.         items.setDetail(“正品行货”);  
  48.         items.setPic(“sdasd.jpg”);  
  49.         items.setCreatetime(new Date());  
  50.         itemsMapper.insert(items);  
  51.     }  
  52.   
  53.   
  54.     //自定义规则来询问  
  55.     @Test  
  56.     public void testSelectByExample() {  
  57.         ItemsExample itemsExample=new ItemsExample();  
  58.         //通过Criteria构造查询条件  
  59.         ItemsExample.Criteria criteria=itemsExample.createCriteria();  
  60.         criteria.andNameEqualTo(“电视机”);  
  61.         //可能回多长记下  
  62.         List<Items> list=itemsMapper.selectByExample(itemsExample);  
  63.         for (int i = 0; i < list.size(); i++) {  
  64.             Items it=list.get(i);  
  65.             System.out.println(it.getId()+”:”+it.getName());  
  66.         }  
  67.     }  
  68.   
  69.   
  70.     //根据主键来查询  
  71.     @Test  
  72.     public void testSelectByPrimaryKey() {  
  73.         Items items=itemsMapper.selectByPrimaryKey(1);  
  74.         System.out.println(items.getName());  
  75.     }  
  76.   
  77.   
  78.     //更新数据  
  79.     @Test  
  80.     public void testUpdateByPrimaryKey() {  
  81.         //对所有字段进行翻新,需要事先查询出来又创新  
  82.         Items items = itemsMapper.selectByPrimaryKey(1);      
  83.         items.setName(“iPhone”);      
  84.         itemsMapper.updateByPrimaryKey(items);  
  85.           
  86.         //如果传入字段不空为才履新,在批量创新受以是道,不待先查询再创新  
  87.         //itemsMapper.updateByPrimaryKeySelective(record);  
  88.     }  
  89.   
  90.   
  91. }  

 

逆向工程的创立与下就讲解到这边

转载请注明出处:http://blog.csdn.net/acmman/article/details/46906871

http://www.bkjia.com/Javabc/1222462.htmlwww.bkjia.comtruehttp://www.bkjia.com/Javabc/1222462.htmlTechArticlemybatis逆向工程之配置,mybatis逆向工程 逆向工程
1.哟是逆向工程
mybaits需要程序员自己编排sql语句,mybatis官方提供逆向工程
可以针对单表…

搭建Spring Boot环境

率先成立maven project,在转变的pom文件被投入依赖,代码如下:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.0</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!--分页插件-->
    <dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper-spring-boot-starter</artifactId>
          <version>1.2.1</version>
    </dependency>

    <!-- alibaba的druid数据库连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.29</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!-- mybatis generator 自动生成代码插件 -->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.2</version>
            <configuration>
                <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                <overwrite>true</overwrite>
                <verbose>true</verbose>
            </configuration>
        </plugin>
    </plugins>
</build>

布局好因后展开maven install,此时小心的坑:
坑一:启动maven install报错:

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.2.RELEASE:repackage (default) on project springboot-mybatis: Execution default of goal org.springframework.boot:spring-boot-maven-plugin:1.5.2.RELEASE:repackage failed: Unable to find main class -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

报错原因是无启动类
解决方式:编写启动类Main.java正常运转!

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

坑二:启动maven install报错:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project springboot-mybatis: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

报错原因:项目之java环境暨计算机环境不切合,例如我之新建项目运作条件为J2SE-1.5,报错是当本人拿该转也jre1.8之后
解决方案:
右键项目——build path——Configure build path——Libraries——双击Jre System
Libraries如下图所示:
图片 3

摘Alternate JRE 如2处的下拉框只有jre,点击3远在之Install
JREs,依次通过add——Standard
VM——next——Directory,选择本机的jdk位置点击finish
在install JREs位置将默认勾选更改jdk,如下图所著,并保存。
图片 4

更maven install项目正常。如下所示:

[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.351 s
[INFO] Finished at: 2018-09-05T21:20:48+08:00
[INFO] Final Memory: 23M/181M
[INFO] ------------------------------------------------------------------------

每当src/main/resources新建文件:application.yml,内容如下所示:

server:
  port: 8080

spring:
    datasource:
        name: test
        url: jdbc:mysql://localhost:3306/test
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver

## 该配置节点为独立的节点
mybatis:
  mapper-locations: classpath:mapper/*.xml

#pagehelper分页插件
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

从那之后springboot环境搭建了!

逆向工程应用

首先应该注意到于pom文件被来配备逆向工程xml文件之位置:src/main/resources/generator/generatorConfig.xml
因而在src/main/resources下新建generator文件夹,并成立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>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="E:\plugins\maven\repo\mysql\mysql-connector-java\5.1.41\mysql-connector-java-5.1.41.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/test" userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成pojo类的位置-->
        <javaModelGenerator targetPackage="com.luis.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <!-- enableSubPackages 是否让schema作为包的后缀-->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 生成mapper接口的位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.luis.mapper" targetProject="src/main/java">
            <!-- enableSubPackages 是否让schema作为包的后缀-->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table schema="" tableName="user"></table>
    </context>
</generatorConfiguration>

因个体条件将配置文件被的配置进行转移,如数据库密码,包名,对许数据库表
所用之数码库表如下:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) NOT NULL,
  `age` int(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES ('1', 'wanger', '22');
INSERT INTO `user` VALUES ('2', 'zhangsan', '18');
INSERT INTO `user` VALUES ('3', 'lisi', '23');
INSERT INTO `user` VALUES ('4', 'wangwu', '21');

部署好后,右键项目,选择run as——Maven build——在底下两处在独家填写:
Goals: mybatis-generator:generate -e
Profiles: generatorConfig.xml
正如图所示:
图片 5

出现如下所示,代码生成成功,刷新项目即可。

[INFO] Generating Example class for table user
[INFO] Generating Record class for table user
[INFO] Generating Mapper Interface for table user
[INFO] Generating SQL Map for table user
[INFO] Saving file UserMapper.xml
[INFO] Saving file UserExample.java
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

要专注的是:逆向工程变更的代码不见面蒙,因而未可知重多次生成。
这里为出个小坑,逆向工程的代码生成后,启动项目会报如下错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userMapper in com.luis.service.impl.UserServiceImpl required a bean of type 'com.luis.mapper.UserMapper' that could not be found.


Action:

Consider defining a bean of type 'com.luis.mapper.UserMapper' in your configuration.

釜底抽薪方案:
1、给生成的mapper接口文件前加注:@Mapper
即可缓解。但需吃各国一个mapper文件前加,繁琐,因而有次类解决办法
2、在启动类前加@MapperScan({“com.luis.mapper”}),其中com.luis.mapper为mapper文件的所在位置。
参考自:http://412887952-qq-com.iteye.com/blog/2392672

分页应用

逆向工程曾变更了entity类,及dao层的mapper接口与*mapper.xml文件,因而/只所以修service层与web层。
首先在UserService中编辑接口,代码如下:

public interface UserService {
    User selectByName(String name);
    List<User> findAllUser(int pageNum, int pageSize);
}

在UserServiceImpl文件进行落实,代码如下所示:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectByName(String name) {
        UserExample example = new UserExample();
        Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(name);
        List<User> users = userMapper.selectByExample(example);
        if (users != null && users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    /**
     * pageNum 开始页数
     * pageSize 每页显示的数据条数
     */
    @Override
    public List<User> findAllUser(int pageNum, int pageSize) {
        //将参数传给方法实现分页
        PageHelper.startPage(pageNum, pageSize);
        UserExample example = new UserExample();
        List<User> list = userMapper.selectByExample(example);
        return list;
    }
}

最终当controller层对查询结果开展收纳,UserController代码如下:

@Controller
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/test")
    public User querUserByName() {
        User user = userService.selectByName("luis");
        System.out.println(user.toString());
        return user;
    }

    @RequestMapping("/list")
    public List<User> querUser() {
        List<User> list = userService.findAllUser(1, 2);
        //获取分页信息
        PageInfo<User> pageInfo = new PageInfo<>(list);
        System.out.println("total:" + pageInfo.getTotal());
        System.out.println("pages:" + pageInfo.getPages());
        System.out.println("pageSize:" + pageInfo.getPageSize());
        return list;
    }
}

测试

先前以项目编制过程遭到一度针对或出现的荒谬进行了总,最后,对项目的力量拓展测试,通过加@RestController注解将数据传到浏览器被。
测试mybatis与springboot,浏览器输入http://localhost:8080/test,浏览器输出:

{"id":1,"name":"wanger","age":22}

分页测试,浏览器输入http://localhost:8080/list,浏览器输出:

[{"id":1,"name":"wanger","age":22},{"id":2,"name":"zhangsan","age":18}]

eclipse输出:

total:4
pages:2
pageSize:2

项目搭建了,具体代码参见github

本文参考了:
http://412887952-qq-com.iteye.com/blog/2392672
https://blog.csdn.net/rico\_rico/article/details/79408474
https://blog.csdn.net/winter\_chen001/article/details/77249029

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图