Mybatis和Spring整合&逆向工程
Mybatis和Spring整合&逆向工程
Mybatis和Spring整合
mybatis整合Spring的思路
目的就是将在SqlMapConfig.xml中的配置移植到Spring的applicationContext.xml文件中
让spring管理SqlSessionFactory
让spring管理mapper对象和dao。
使用spring和mybatis整合开发mapper代理及原始dao接口。
自动开启事务,自动关闭 sqlsession.
让spring管理数据源( 数据库连接池)
导入相关的jar包
配置配置文件
log4j.properties
SqlMapconfig.xml
applicationContext.xml
整合开发原始dao接口
在 applicationContext.xml配置SqlSessionFactory和数据源(DBCP连接池)
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 最大连接数 -->
<property name="maxActive" value="20" />
<!-- 最大等待时间 -->
<property name="maxWait" value="8000" />
<!-- 最大空闲数 -->
<property name="maxIdle" value="3" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加载Mybatis的核心配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml" />
<!-- 别名包扫描 -->
<property name="typeAliasesPackage" value="com.syj.mybatis.pojo"/>
</bean>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
开发Dao接口
public interface UserDao {
// 根据id查询用户的信息
public User findUserById(int id) throws Exception;
// 根据姓名进行模糊查询
public List<User> findUserByName(String username) throws Exception;
}
1
2
3
4
5
6
7
Dao实现类
//通常情况下我们回去继承自SqlSessionDaoSupport就可以直接在Spring的配置中直接注入sqlSessionFactory
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public User findUserById(int id) throws Exception {
SqlSession sqlSession = this.getSqlSession();
User user = sqlSession.selectOne("user.findUserById", id);
return user;
}
@Override
public List<User> findUserByName(String username) throws Exception {
SqlSession sqlSession = this.getSqlSession();
List<User> list = sqlSession.selectList("user.findUserByName", username);
return list;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
在Spring中配置Dao
<!-- 传统Dao配置 -->
<bean id="userDao" class="com.syj.mybatis.dao.impl.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
1
2
3
4
测试
public class UserDaoTest {
private ApplicationContext applicationContext;
@Before
public void init() {
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
@Test
public void testFindUserById() throws Exception {
UserDao userDao = applicationContext.getBean(UserDao.class);
User user = userDao.findUserById(32);
System.out.println(user);
}
@Test
public void testFindUserByName() throws Exception {
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
List<User> list = userDao.findUserByName("张");
for (User user : list) {
System.out.println(user);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
整合开发mapper代理的方法
编写mapper接口
public interface UserMapper {
// 根据id查询用户的信息
public User findUserById(int id) throws Exception;
// 根据姓名进行模糊查询
public List<User> findUserByName(String username) throws Exception;
// 插入用户
public void insertUser(User user) throws Exception;
}
1
2
3
4
5
6
7
8
9
10
编写mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.syj.mybatis.mapper.UserMapper">
<!-- 根据id查询用户信息 -->
<select id="findUserById" parameterType="int" resultType="user">
SELECT * FROM USER WHERE id = #{id};
</select>
<!-- 根据名字模糊查询用户的信息 -->
<select id="findUserByName" resultType="user"
parameterType="string">
SELECT * FROM USER WHERE username like '%${value}%';
</select>
<!-- 保存用户信息 -->
<insert id="insertUser" parameterType="user">
<selectKey keyProperty="id" order="AFTER" resultType="int">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO USER (username,birthday,sex,address)
VALUES
(#{username},#{birthday},#{sex},#{address})
</insert>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
在Spring的配置文件中配置mapper.xml文件的映射
<!-- mapper代理Dao开发,第一种方式 -MapperFactoryBean -->
<!--
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" >
<!-- mapperInterface的mapper接口 -->
<property name="mapperInterface" value="com.syj.mybatis.mapper.UserMapper" />
<!-- MapperFactoryBean继承自SqlSessionDaoSupport -->
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
-->
<!-- mapper动态代理Dao开发,第二种方式,包扫描器(推荐使用)
MapperScannerConfigurer:mapper的扫描器,将包下面的mapper接口自动创建代理对象
自动创建到Spring容器中,bean的id就是mapper的类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置扫描包的路径,如果要扫描多个包,中间使用半角 , 号隔开 -->
<property name="basePackage" value="com.syj.mybatis.mapper"/>
<!-- 不使用sqlSessionFactory的原因就是和上面的
<context:property-placeholder location="classpath:jdbc.properties" />
有 冲突
-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
测试
逆向工程
什么是逆向工程
mybatis需要程序员自己编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行所需要的代码(mapper.java、mapper.xml、pojo…),可以让程序员将更多的精力放在繁杂的业务逻辑上。
企业实际开发中,常用的逆向工程方式:由数据库的表 —> java代码。
之所以强调单表两个字,是因为Mybatis逆向工程生成的Mapper所进行的操作都是针对单表的,在大型项目中,很少有复杂的多表关联查询,所以作用还是很大的。
下载逆向工程:
https://github.com/mybatis/generator/releases
逆向工程的使用
如何运行逆向工程
官网:http://www.mybatis.org/generator/index.html
我们使用Java工程生成逆向工程
使用逆向工程生成代码
java工程结构
GeneratorSqlmap.java
package com.syj.mybatis;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
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 GeneratorSqlmap {
public void generator() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
// 指定逆向工程的配置文件位置
File configFile = new File("./config/generatorConfig.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);
}
public static void main(String[] args) throws Exception {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis168" userId="root"
password="root">
</jdbcConnection>
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
userId="yycg"
password="yycg">
</jdbcConnection> -->
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.syj.mybatis.po"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.syj.mybatis.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.syj.mybatis.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail"></table>
<table tableName="user"></table>
<!-- <table schema="" tableName="sys_user"></table>
<table schema="" tableName="sys_role"></table>
<table schema="" tableName="sys_permission"></table>
<table schema="" tableName="sys_user_role"></table>
<table schema="" tableName="sys_role_permission"></table> -->
<!-- 有些表的字段需要指定java类型
<table schema="" tableName="">
<columnOverride column="" javaType="" />
</table> -->
</context>
</generatorConfiguration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
配置文件需要修改的内容:
数据库驱动、地址、用户名、密码
POJO类、mapper接口、mapper映射文件生成的位置
指定数据表
配置完成之后运行GeneratorSqlmap.java中的main方法就会生成对应数据表的代码,生成后记得右键项目名刷新。如果需要再次生成,一定要记得先把原来生成的删除。
生成的代码结构目录
我们可以将生成的代码拷贝到工程中进行测试
逆向工程提供的方法
查询
方法 作用
selectByExample(TbItemDescExample example)** 通过特定限制条件查询信息,example用于生成一个Criteria对象来设置查询条件
selectByPrimaryKey(Long itemId)** 通过主键查询
selectByExampleWithBLOBs(TbItemDescExample example) 根据特定限制条件查询,返回值包含类型为text的列(默认查询并不会返回该列的信息)。example用于生成一个Criteria对象来设置查询条件,具体使用方法和方法1是一样的,唯一的把不同就是返回值是所有列。
不能指定查询的列,只能够查询所有列。
selectByExample(TbItemDescExample example)
example用于生成一个Criteria对象来设置查询条件
@Test
public void testSelectByExample() {
// 生成表Example对象
UserExample example = new UserExample(http://www.my516.com);
// 生成criteria对象用于设置查询条件
Criteria criteria = example.createCriteria();
criteria.andIdIn(Arrays.asList(1, 16, 26));
// 1、查询出符合条件的指定信息
// List<User> list = userMapper.selectByExample(example);
// for (User user : list) {
// System.out.println(user);
// }
// 2、查询总数
int countByExample = userMapper.countByExample(example);
System.out.println(countByExample);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Criteria对象设置条件逆向工程会根据指定的表去生成多中方法
selectByPrimaryKey(Long itemId) 、
通过主键查询
selectByExampleWithBLOBs(TbItemDescExample example)
根据特定限制条件查询,查询大文本
保存
相同点: 方法传入的参数都是POJO,返回值都是int类型的受影响的行数。
insert: 插入所有的信息,如果传入的对象某一属性为空,则插入空,如果数据库中设置了默认值,默认值就失效了
insertSelective: 他只会插入含有数据的属性,对于为空的属性,不予以处理,这样的话如果数据库中设置有默认值,就不会被空值覆盖了。
更新
第一类:根据特定限制条件进行更新
参数1:Pojo名 record -> 要更新的对象
参数2:Pojo名+Example example -> 生成一个Criteria对象来设置查询条件
方法 作用
updateByExample(User record, UserExample example) 根据特定的限制条件进行更新除了text类型(数据库)的所有列。
updateByExampleSelective(Userrecord, UserExample example) 根据特定的限制条件更新所有设置了值的列。
第二类:根据ID进行更新
参数:Pojo名 record -> 要更新的对象
方法 作用
updateByPrimaryKey(User record) 通过ID更新除了text类型(数据库)的所有列
updateByPrimaryKeySelective(User record) 通过ID更新所有设置了值的列。
删除
方法1:根据特定限制条件删除,具体使用的方法和查询的时候是一样的。
方法2:根据主键删除。
---------------------
Mybatis和Spring整合&逆向工程的更多相关文章
- Mybatis(六) Spring整合mybatis
心莫浮躁~踏踏实实走,一步一个脚印,就算不学习,玩,能干嘛呢?人生就是那样,要找点有意思,打发时间的事情来做,而钻研技术,动脑动手的过程,还是比其他工作更有意思些~ so,努力啥的都是强迫自己做自以为 ...
- MyBatis学习(四)MyBatis和Spring整合
MyBatis和Spring整合 思路 1.让spring管理SqlSessionFactory 2.让spring管理mapper对象和dao. 使用spring和mybatis整合开发mapper ...
- Mybatis与Spring整合,使用了maven管理项目,作为初学者觉得不错,转载下来
转载自:http://www.cnblogs.com/xdp-gacl/p/4271627.html 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn archetype ...
- Mybatis+struts2+spring整合
把student项目改造成ssm struts2 +mybatis+spring 1,先添加spring支持:类库三个,applicationContext.xml写在webinf下四个命名空间,监 ...
- mybatis与spring整合(基于配置文件)
本文主要介绍了如何将mybatis和spring整合在一起使用,本人使用的是mybatis3.05 + spring3.1.0M2 ,使用dbcp作为数据库连接池. 1.编写数据访问接口(UserDa ...
- mybatis与spring整合时读取properties问题的解决
在学习mybatis与spring整合是,想从外部引用一个db.properties数据库配置文件,在配置文件中使用占位符进行引用,如下: <context:property-placehold ...
- Spring+SpringMVC+MyBatis深入学习及搭建(九)——MyBatis和Spring整合
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6964162.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(八)--My ...
- Mybatis第五篇【Mybatis与Spring整合】
Mybatis与Spring整合 既然我们已经学了Mybatis的基本开发了,接下来就是Mybatis与Spring的整合了! 以下使用的是Oracle数据库来进行测试 导入jar包 aopallia ...
- MyBatis 与 Spring 整合
MyBatis-Spring 项目 目前大部分的 Java 互联网项目,都是用 Spring MVC + Spring + MyBatis 搭建平台的. 使用 Spring IoC 可以有效的管理各类 ...
随机推荐
- [Java] String类, StringBuffer类
1. String 类 1. 创建: String s1 = new String; s1 = "abc"; String s2 = new String("abc&qu ...
- Java中gcRoot和引用类型
看到一个老问题,Java是如何判定回收哪些对象的? 答:从gcRoot根搜索不可达,且标记清理一次之后仍没有被复活的对象,会被认定为垃圾对象进行清理.注意在Java中没有对象的作用域,只有对象的引用的 ...
- CentOS6.6详细安装教程(图文教程)
CentOS 6.x最新版本为CentOS 6.6,下面介绍CentOS 6.6的具体安装配置过程,需要的朋友可以参考下说明: Centos6.6 下载地址:thunder://QUFodHRwOi8 ...
- Vue Router的配置
1.beforeEnter function requireAuth (route, redirect, next) { if (!auth.loggedIn()) { redirect({ path ...
- Codeforces Round #422 (Div. 2)D. My pretty girl Noora(递推+数论)
传送门 题意 对于n个女孩,每次分成x人/组,每组比较次数为\(\frac{x(x+1)}{2}\),直到剩余1人 计算\[\sum_{i=l}^{r}t^{i-l}f(i)\],其中f(i)代表i个 ...
- poj1651【区间DP·基础】
题意: 给你一串数字,头尾不能动,每次取出一个数字,这个数字贡献=该数字与左右相邻数字的乘积,求一个最小值. 思路: 用dp[s][t]去代表s到t的最小值,包括a[s]和a[t],然后从区间为3开始 ...
- 3dmax学习资料记录
max2015 官方文档 http://help.autodesk.com/view/3DSMAX/2015/CHS/?guid=GUID-D015E335-EFB3-43BF-AB27-C3CB09 ...
- Servlet3.0-使用注解定义过滤器(Filter)
本人正在学javaweb,遇到了在eclipse中,servlet3.0过滤器需不需要配置web.xml文件?通过实践得出结论,不用配置,只需要@WebFilter(filterName=" ...
- bzoj 5499: [2019省队联测]春节十二响【堆】
首先看两条链怎么合并,贪心可得是从大到小取max,多条链同理 所以dfs合并子树的大根堆即可,注意为了保证复杂度,合并的时候要合并到最长链上,证明见长链剖分 #include<iostream& ...
- bzoj 4622: [NOI 2003] 智破连环阵【dfs+匈牙利算法】
一个炸弹炸一个区间的武器,想到二分图匹配 但是直接dfs断点显然不行,预处理出dis[i]为i到m的至多值来最优性剪枝,并且标记ok[i][j]为炸弹i可以炸到j武器,mx[i][j]为i炸弹从j武器 ...