mybatis逆向工程案例

第一步引入jar包引入依赖

第二步

创建DB相应的表,并插入数据

CREATE TABLE `departments`(
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(20) NOT NULL UNIQUE,
`tele_num` INT(30)
)

CREATE TABLE `students` (
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(20) NOT NULL UNIQUE,
`password` VARCHAR(32) NOT NULL,
`email` VARCHAR(50) DEFAULT NULL,
`d_id` INT(11),
CONSTRAINT `fk_id` FOREIGN KEY(`d_id`) REFERENCES `departments`(id)
)

第三步配置代码生成器的运行环境(配置generatorconfiguration文件)

<?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>
    <!--数据源-->
    <context id="MyGenerator" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.1.8:3306/book"
                        userId="root"
                        password="3333">
        </jdbcConnection>

        <!--类型解析器-->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!--指定javabean生成策略,指定目标包名和目标工程名-->
        <javaModelGenerator targetPackage="classes.com.aspire.study.pojo" targetProject=".\src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!--指定sqlmapper映射策略-->
        <sqlMapGenerator targetPackage="conf.mybatis.mappers"  targetProject=".\src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!--指定接口生成映射策略-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="classes.com.aspire.study.dao"  targetProject=".\src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!--指定数据库表映射策略-->
        <table tableName="students" domainObjectName="Student" />
        <table tableName="departments" domainObjectName="Department" />

    </context>
</generatorConfiguration>

接下来见证奇迹的时刻,启动项目,发现什么都没生成,这是怎么肥四?

因为我们光配置了,并没有去加载config,并执行之。

第四步 启动之,新建测试类

package classes.com.aspire.study.test;

import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class GenerantorTest {
    @Test
    public void testGenerator() throws Exception {
        URL url = GenerantorTest.class.getResource("/conf/generator-config.xml");
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File(url.toURI());
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

执行之,查看列表

这就是传说中的逆向工程吗?爱了。。爱了。。

赶紧来测试一下,看看是不是像它官方文档上吹嘘的那样厉害。

首先配置db的properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.8:3306/book
jdbc.username=root
jdbc.password=xxxx

配置mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- dtd是对配置文件的约束,配置文件必须根据它的规定写 -->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 读取存放连接数据库信息的配置文件 -->
    <properties resource="conf/jdbc.properties"/>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- 配置环境,develop是开发环境 -->
    <environments default="develop">
        <!-- 配置具体的环境,开发环境 -->
        <environment id="develop">
            <!-- 配置事务管理,指定为JDBC类型 -->
            <transactionManager type="JDBC" />
            <!-- 设置数据源,类型为POOLED数据池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="conf/mybatis/mappers/StudentMapper.xml"/>
        <mapper resource="conf/mybatis/mappers/DepartmentMapper.xml"/>
    </mappers>
</configuration>


创建sqlSession对象

@Test
    public void testCrud() throws IOException {
        InputStream is= Resources.getResourceAsStream("conf/mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        try {
            StudentMapper mapper=sqlSession.getMapper(StudentMapper.class);
            List<Student> studentList=mapper.selectByExample(null);
            for(Student student:studentList){
                System.out.println(student);
            }

        }finally {
            sqlSession.close();
        }
    }

结果

复杂点的and条件查询

    @Test
    public void testCrud() throws IOException {
        InputStream is= Resources.getResourceAsStream("conf/mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        try {
            StudentMapper mapper=sqlSession.getMapper(StudentMapper.class);

            StudentExample example=new StudentExample();
            StudentExample.Criteria criteria=example.createCriteria();
            criteria.andEmailLike("%node%");
            criteria.andDIdEqualTo(1);
            List<Student> studentList=mapper.selectByExample(example);
            for(Student student:studentList){
                System.out.println(student);
            }

        }finally {
            sqlSession.close();
        }
    }

结果

再来个or条件的

    @Test
    public void testCrud() throws IOException {
        InputStream is= Resources.getResourceAsStream("conf/mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        try {
            StudentMapper mapper=sqlSession.getMapper(StudentMapper.class);

            StudentExample example=new StudentExample();

            StudentExample.Criteria criteria1=example.createCriteria();
            criteria1.andEmailLike("%node%");
            criteria1.andDIdEqualTo(1);

            StudentExample.Criteria criteria2=example.createCriteria();
            criteria2.andDIdEqualTo(3);
            example.or(criteria2);

            List<Student> studentList=mapper.selectByExample(example);
            for(Student student:studentList){
                System.out.println(student);
            }

        }finally {
            sqlSession.close();
        }
    }

没有问题,简直稳如老狗!今天的学习就到这里了,我继续研究redis去了。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值