IDEA整合SSM框架之配置数据持久层Mybatis
-
配置数据持久层-Mybatis
-
pom.xml中引入相关依赖包
- 创建数据库jdbc.properties配置文件
- 创建dao、entity、mapper包路径
- 创建mybatis配置文件spring-mybatis.xml
- 在pom.xml中配置,将xml打包在war中
- 生成dao、entity、mapper
- 实现数据库增删改查接口
-
创建接口TUserService
* 创建类TUserServiceImpl实现TUserService接口
* 创建TUserController
* 配置文件spring-mvc.xml
* 返回数据工具RestResult- 运行项目,浏览器测试接口
配置数据持久层-Mybatis
- Mybatis是数据持久层框架,简单易学;
- SQL写在xml里,便于统一管理和优化;
- 通过提供DAO层,将业务逻辑和数据访问逻辑分离,SQLl和代码的分离,提高了可维护性;
- 提供映射标签,支持对象与数据库的orm字段关系映射;
- 提供xml标签,支持编写动态sql;
pom.xml中引入相关依赖包
-
在pom.xml的节点中引入一下依赖包
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 1 <!--spring-jdbc-->
2 <dependency>
3 <groupId>org.springframework</groupId>
4 <artifactId>spring-jdbc</artifactId>
5 <version>4.1.4.RELEASE</version>
6 </dependency>
7 <!--数据库连接池-->
8 <dependency>
9 <groupId>com.alibaba</groupId>
10 <artifactId>druid</artifactId>
11 <version>1.1.14</version>
12 </dependency>
13 <!--数据库连接驱动-->
14 <dependency>
15 <groupId>mysql</groupId>
16 <artifactId>mysql-connector-java</artifactId>
17 <version>5.1.6</version>
18 </dependency>
19 <!--spring配置mybatis包 -->
20 <dependency>
21 <groupId>org.mybatis</groupId>
22 <artifactId>mybatis-spring</artifactId>
23 <version>2.0.0</version>
24 </dependency>
25 <!--mybatis配置-->
26 <dependency>
27 <groupId>org.mybatis</groupId>
28 <artifactId>mybatis</artifactId>
29 <version>3.5.0</version>
30 </dependency>
31
32
创建数据库jdbc.properties配置文件
-
在resources文件加下创建properties包(不存在时创建,可有可无),再创建jdbc.properties文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 1 #数据库连接信息,数据库地址,数据库,用户名,密码,驱动以及其他信息
2 jdbc.url=jdbc:mysql://localhost:3306/demo?roundRobinLoadBalance=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC
3 jdbc.username=root
4 jdbc.password=mysql
5 jdbc.driver=com.mysql.jdbc.Driver
6 jdbc.initialSize=5
7 jdbc.minIdle=5
8 jdbc.maxActive=100
9 jdbc.maxWait=100000
10 jdbc.testOnBorrow=false
11 jdbc.testOnReturn=false
12 jdbc.testWhileIdle=true
13 jdbc.timeBetweenEvictionRunsMillis=60000
14 jdbc.minEvictableIdleTimeMillis=25200000
15 jdbc.removeAbandoned=true
16 jdbc.removeAbandonedTimeout=1800
17 jdbc.logAbandoned=true
18
19
创建dao、entity、mapper包路径
- 在main/java 下创建dao、entity、mapper包路径
创建mybatis配置文件spring-mybatis.xml
这个文件的主要作用就是整合spring与mybatis, 同时配置数据库数据源、数据库连接池、 dao、entity、mapper路径,以及配置数据库事务与spring配置
-
在resources文件加下创建xml包(不存在时创建,可有可无),再创建spring-mybatis.xml文件,右击xml包,new->XML Confiuration File -> Spring Config,
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 1<?xml version="1.0" encoding="UTF-8"?>
2<beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:context="http://www.springframework.org/schema/context"
5 xmlns:tx="http://www.springframework.org/schema/tx"
6 xsi:schemaLocation="
7 http://www.springframework.org/schema/tx
8 http://www.springframework.org/schema/tx/spring-tx.xsd
9 http://www.springframework.org/schema/beans
10 http://www.springframework.org/schema/beans/spring-beans.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context.xsd
13 ">
14 <!--扫描JDBC配置文件-->
15 <!--ignore-unresolvable忽略占位符,解决对个context:property-placeholder标签无法解析报错的问题-->
16 <context:property-placeholder location="classpath:properties/jdbc.properties" ignore-unresolvable="true"/>
17 <!--配置数据库连接池-->
18 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
19 <property name="driverClassName" value="${jdbc.driver}"/>
20 <property name="url" value="${jdbc.url}"/>
21 <property name="username" value="${jdbc.username}"/>
22 <property name="password" value="${jdbc.password}"/>
23 <property name="initialSize" value="${jdbc.initialSize}"/>
24 <property name="maxActive" value="${jdbc.maxActive}"/>
25 <property name="maxWait" value="${jdbc.maxWait}"/>
26 <property name="minIdle" value="${jdbc.minIdle}"/>
27 <property name="testOnBorrow" value="${jdbc.testOnBorrow}"/>
28 <property name="testOnReturn" value="${jdbc.testOnReturn}"/>
29 <property name="testWhileIdle" value="${jdbc.testWhileIdle}"/>
30 <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>
31 <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>
32 <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/>
33 <property name="removeAbandoned" value="${jdbc.removeAbandoned}"/>
34 <property name="logAbandoned" value="${jdbc.logAbandoned}"/>
35 </bean>
36
37 <!--配置数据库连接工程-->
38 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
39 <!--配置数据源-->
40 <property name="dataSource" ref="dataSource"/>
41 <!--扫描实体类包路径-->
42 <property name="typeAliasesPackage" value="com.xiao.demo.springmvc.mybatis.entity"/>
43 <!--扫描Mapper文件路径 文件命名方式***Mapper.xml-->
44 <property name="mapperLocations" value="classpath:com/xiao/demo/springmvc/mybatis/mapper/*Mapper.xml"/>
45 </bean>
46 <!--扫描Mapper接口-->
47 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
48 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
49 <!--mapper接口dao包路径-->
50 <property name="basePackage" value="com.xiao.demo.springmvc.mybatis.dao"/>
51 </bean>
52 <!--负责管理MyBatis的SqlSession-->
53 <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
54 <constructor-arg index="0" ref="sqlSessionFactory"/>
55 </bean>
56
57 <!--开启数据库事务-->
58 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
59 <property name="dataSource" ref="dataSource"/>
60 </bean>
61 <!--transactionManager 指定事务管理器-->
62 <tx:annotation-driven proxy-target-class="false" transaction-manager="transactionManager"/>
63</beans>
64
65
在pom.xml中配置,将xml打包在war中
-
在pom.xml中配置,将*.Mapper.xml文件打包在war包中,不然会报mapper路径不存在
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 1<resources>
2 <resource>
3 <directory>src/main/java</directory>
4 <includes>
5 <include>**/*.xml</include>
6 </includes>
7 <filtering>true</filtering>
8 </resource>
9 <resource>
10 <directory>src/main/resources</directory>
11 <includes>
12 <include>*.*</include>
13 <include>**.*</include>
14 <include>**/*.*</include>
15 </includes>
16 </resource>
17</resources>
18
19
生成dao、entity、mapper
使用mybatis-generator插件生成dao、entity、mapper,请参照一下案例
IDEA整合SSM框架之配置mybatis-generator插件(四)
实现数据库增删改查接口
通过已配置好的mybatis对数据库进行增删改查功能,并实现接口访问
创建接口TUserService
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 1/**
2 * 用户业务层接口
3 *
4 * @author xiaog.li
5 * @date 2019/8/5 23:21
6 */
7public interface TUserService {
8 /**
9 * 增
10 *
11 * @return int
12 * @date 2019/8/6 21:38
13 */
14 Object add();
15
16 /**
17 * 根据主键删除
18 *
19 * @return int
20 * @date 2019/8/6 21:38
21 */
22 Object delete(Integer id);
23
24 /**
25 * 更新
26 *
27 * @return
28 */
29 Object update(Integer id);
30
31 /**
32 * 查询
33 *
34 * @param id
35 * @return
36 */
37 Object select(Integer id);
38
39}
40
41
创建类TUserServiceImpl实现TUserService接口
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 1实现TUserService接口,处理业务逻辑
2@Service 注解为业务逻辑层
3@Component 无明确分类,可以被注入到spring容器进行管理
4@Repository 数据持久层 这里未使用
5
6/**
7 * 业务实现
8 *
9 * @author xiaog.li
10 * @date 2019/8/6 22:41
11 */
12@Service
13public class TUserServiceImpl implements TUserService {
14
15 @Autowired
16 private TUserMapper tUserMapper;
17
18 @Override
19 public Object add() {
20 TUser user = new TUser();
21 user.setRealName("李");
22 user.setUserName("四");
23 user.setSex("男");
24 user.setTel("156****8888");
25 user.setCreateTime(new Date());
26 user.setUpdateTime(new Date());
27 return tUserMapper.insertSelective(user) > 0 ?
28 RestResult.ok("添加成功") : RestResult.fail("添加失败");
29 }
30
31 @Override
32 public Object delete(Integer id) {
33 return tUserMapper.deleteByPrimaryKey(id) > 0 ?
34 RestResult.ok("删除成功") : RestResult.fail("删除失败");
35 }
36
37 @Override
38 public Object update(Integer id) {
39 TUser user = new TUser();
40 user.setRealName("王");
41 user.setUserName("五");
42 user.setSex("女");
43 user.setTel("156****6666");
44 user.setCreateTime(new Date());
45 user.setUpdateTime(new Date());
46 user.setId(id);
47 return tUserMapper.updateByPrimaryKeySelective(user) > 0 ?
48 RestResult.ok("更新成功") : RestResult.fail("更新失败");
49 }
50
51 @Override
52 public Object select(Integer id) {
53 TUser user = tUserMapper.selectByPrimaryKey(id);
54 return user==null?
55 RestResult.fail("查询失败"):RestResult.ok("查询成功",user);
56 }
57}
58
59
创建TUserController
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 1@RestController注解类,该类中的所有接口都返回数据
2@Controller注解类,没有使用@ResponseBody注解的方法,返回网页,jsp或者html
3@Controller注解类,@ResponseBody注解方法,功能@RestController注解相同,
4如果所有接口都返回String数据,直接使用@RestController注解类,反之使用组合注解
5@RequestMapping注解实现访问地址,
6value是接口地址,
7produces返回数据类型以及编码格式,可解决中文乱码问题,
8method 请求方式
9
10/**
11 * 控制层 映射对外接口请求地址
12 */
13@RestController
14@RequestMapping(value = "/user")
15public class TUserController {
16 @Autowired
17 private TUserService tUserService;
18
19 @RequestMapping(value = "/add", produces = "application/json;charset=utf-8")
20 public Object add() {
21 return tUserService.add();
22 }
23
24 @RequestMapping(value = "/delete", produces = "application/json;charset=utf-8")
25 public Object delete(Integer id) {
26 return tUserService.delete(id);
27 }
28
29 @RequestMapping(value = "/update", produces = "application/json;charset=utf-8")
30 public Object update(Integer id) {
31 return tUserService.update(id);
32 }
33
34 @RequestMapping(value = "/select", produces = "application/json;charset=utf-8")
35 public Object select(Integer id) {
36 return tUserService.select(id);
37 }
38}
39
40
配置文件spring-mvc.xml
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 1<?xml version="1.0" encoding="UTF-8"?>
2<beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:context="http://www.springframework.org/schema/context"
5 xmlns:mvc="http://www.springframework.org/schema/mvc"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/context
9 http://www.springframework.org/schema/context/spring-context.xsd
10 http://www.springframework.org/schema/mvc
11 http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12 <!--扫码控制器路径-->
13 <context:component-scan base-package="com.xiao.demo.springmvc.controller"/>
14 <!--扫码控制器服务层-->
15 <context:component-scan base-package="com.xiao.demo.springmvc.service"/>
16 <!--启动注解-->
17 <mvc:annotation-driven>
18 <mvc:message-converters>
19 <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
20 <property name="supportedMediaTypes">
21 <list>
22 <value>text/html;charset=UTF-8</value>
23 <value>application/json</value>
24 <value>application/xml;charset=UTF-8</value>
25 </list>
26 </property>
27 <property name="features">
28 <list>
29 <value>DisableCheckSpecialChar</value>
30 </list>
31 </property>
32 </bean>
33 </mvc:message-converters>
34 </mvc:annotation-driven>
35
36</beans>
37
38
返回数据工具RestResult
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 1/**
2 * 返回数据实体类
3 *
4 * @author xiaog.li
5 * @date 2019/8/6 21:55
6 */
7public class RestResult {
8
9 private static Map<String, Object> result(String code, String msg, Object data) {
10 Map<String, Object> map = new HashMap<>();
11 map.put("code", code);
12 map.put("msg", msg);
13 map.put("data", data);
14 return map;
15 }
16
17 public static Map<String, Object> ok(String msg, Object data) {
18 return result("0", msg, data);
19 }
20
21 public static Map<String, Object> ok(String msg) {
22 return ok(msg, null);
23 }
24
25 public static Map<String, Object> ok() {
26 return ok("操作成功");
27 }
28
29 public static Map<String, Object> fail(String msg) {
30 return result("1", msg, null);
31 }
32
33 public static Map<String, Object> fail() {
34 return fail("操作失败");
35 }
36}
37
38
运行项目,浏览器测试接口
- 新增
- 删除
- 更新
- 查询