您的位置:首页 > 其它

Maven下SSM项目整合笔记02:mybatis配置文件以及逆向工程

2017-09-11 11:02 716 查看

配置文件

mybatis的全局配置文件

可以使用官方文档,搜索mybatis-》帮助文档-》http://www.mybatis.org/mybatis-3/

在getting start扎到配置文件的文件头:

在configuration xml里面找到setting:里面能够找到对应的自动设置:

以下是mybatis的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value=""/>
</settings>
<!-- 别名 -->
<typeAliases>
<package name="com.zr.crud.bean"/>
</typeAliases>

</configuration>


创建数据表:

创建表后导出的表结构如下(这里添加外键是为了保证数据的安全性,逻辑上可以不要):

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tbl_dept
-- ----------------------------
DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept` (
`dept_id` int(11) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(255) NOT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tbl_emp
-- ----------------------------
DROP TABLE IF EXISTS `tbl_emp`;
CREATE TABLE `tbl_emp` (
`emp_id` int(11) NOT NULL AUTO_INCREMENT,
`emp_name` varchar(255) NOT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`emd_id`),
KEY `fk_emp_dept` (`d_id`),
CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


使用mybatis提供的逆向工程

使用逆向工程创建需要的bean以及mapper:

点击quick start按照步骤使用:

- 1.首先引入generator的相关jar包:pom.xml里面添加:

<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator</artifactId>
<version>1.3.5</version>
</dependency>


这里因为导入pom文件仍然无法读取,所以采用吧jar包导入本地的方法,使用maven把文件导入本地仓库:

-Dfile为下载文件的位置,这里指定版本号,将下载的jar包导入本地的仓库,仓库位置可以看maven目录下的conf文件夹下的settings.xml:

使用以下命令导入:

mvn install:install-file -Dfile=d:\BaseCodes\mybatis-generator-core-1.3.5.jar -DgroupId=com.google.code -DartifactId=mybatis-generator-core -Dversion=1.3.5 -Dpackaging=jar


之后在pom连添加:

<dependency>
<groupId>com.google.code</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>


2.使用官方模板创建配置文件(mgb.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>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 配置数据库的连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_crud" userId="root" password="mysqladmin">
</jdbcConnection>

<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 指定javabean生成的位置 -->
<javaModelGenerator targetPackage="com.zr.crud.bean"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>

<!-- 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="mapper"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>

<!-- 指定dao接口生成的位置,mapper接口 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.zr.crud.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>

<!-- 指定每个表的生成策略 -->
<!-- tableName表名 -->
<!-- domainObjectName生成类的名字 -->
<table tableName="tbl_emp" domainObjectName="Employee"></table>
<table tableName="tbl_dept" domainObjectName="Department"></table>
</context>
</generatorConfiguration>


之后可以查看文档中的Running MyBatis Generator:

http://www.mybatis.org/generator/running/running.html

这里使用java代码的方式运行:

package com.zr.crud.test;

import java.io.*;
import java.util.*;

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;

public class MBGTest {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File( System.getProperty("user.dir")+"\\mgb.xml");
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);
}
}


运行后dao类报错:

The import org.apache.ibatis cannot be resolved

这个时候需要导入对应的包:

在pom.xml中添加:

<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-core</artifactId>
<version>3.0</version>
</dependency>


至此,生成完成。

修改相关配置文件

此时,在生成代码的基础上开始修改:

- 因为我们在查询时需要多表关联查询,所以在生成的com.zr.crud.bean.Employee类中添加Department字段:

//自动生成的基础上添加的成员department用于方便关联查询
private Department department;

public Department getDepartment() {
return department;
}

public void setDepartment(Department department) {
this.department = department;
}


在com.zr.crud.dao.EmployeeMapper类中添加方法关联查询:

//新增加的方法:
//1.selectByExampleWithDept
//2.selectByPrimaryKeyWithDept
List<Employee> selectByExampleWithDept(EmployeeExample example);

Employee selectByPrimaryKeyWithDept(Integer emdId);


在Mapper配置文件EmployeeMapper.xml中添加对应sql语句:

– 返回集合:关联查询返回多个表的数据,使用association来关联:

<resultMap type="com.zr.crud.bean.Employee" id="WithDeptResultMap">
<id column="emp_id" jdbcType="INTEGER" property="empId" />
<result column="emp_name" jdbcType="VARCHAR" property="empName" />
<result column="gender" jdbcType="CHAR" property="gender" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="d_id" jdbcType="INTEGER" property="dId" />
<!-- 使用association来对应查询的结果 -->
<!-- property为类中的变量名 column为 javaType为数据类型 -->
<association property="department" javaType="com.zr.crud.bean.Department">
<!-- column为返回的列名 -->
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName" jdbcType="VARCHAR"/>
</association>
</resultMap>


– 新建需要查询的列:

<sql id="WithDept_Column_List">
e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id,
d.dept_name
</sql>


– 使用右连接关联查询:

<select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="WithDept_Column_List" />
FROM tbl_emp e LEFT JOIN tbl_dept d on e.d_id=d.dept_id
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
select
<include refid="WithDept_Column_List" />
FROM tbl_emp e LEFT JOIN tbl_dept d on e.d_id=d.dept_id
where emp_id = #{empId,jdbcType=INTEGER}
</select>


测试mapper

使用Spring的单元测试,需要在pom.xml中添加对应的依赖关系:

<!-- 导入Spring的测试模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>


编写测试类查看数据:

package com.zr.crud.test;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.zr.crud.bean.Department;
import com.zr.crud.bean.DepartmentExample;
import com.zr.crud.dao.DepartmentMapper;

/**
* 测试dao层的工作
* Spring的项目推荐使用Spring的单元测试,可以自动注入我们需要的组件
* 1.在pom.xml中导入SpringTest的依赖
* 2.使用注解@ContextConfiguration指定Spring配置文件的位置
* 3.直接autowired要使用的组件即可
* @author asus
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class MapperTest {

@Autowired
DepartmentMapper departmentMapper;
/**
* 测试DepartmentMapper
*/
@Test
public void testCRUD_Dept() {
List<Department> d_list = departmentMapper.selectByExample(new DepartmentExample());
for (Department department : d_list) {
System.out.println(department.getDeptId()+" : " + department.getDeptName());
}
}
}


控制台输出:



可以看到数据成功显示。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐