springboot-mybatis xml配置
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github 。
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
本机主要介绍mybatis通过xml配置方式操作数据库,这也是项目开发中通用的一种,将sql编写在xml中,便于维护、开发、升级等,不需要做太多的改动即可使用。
创建maven项目
在pom.xml中引入依赖包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example.springboot</groupId> <artifactId>springboot-mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-mybatis</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.12.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.7</java.version> <!--mybatis版本--> <mybatis-spring.version>1.3.2</mybatis-spring.version> <!--mybatis 分页插件版本--> <mybatis-pagehelper.version>4.1.0</mybatis-pagehelper.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> <scope>test</scope> </dependency> <!--引入数据库连接--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--mybatis分页插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${mybatis-pagehelper.version}</version> </dependency> </dependencies> <build> <finalName>springboot-mybatis</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>在src/main/resources/application.properties配置文件中增加数据库连接
#服务端口 #server.port=8088 #server.context-path=/springboot #mysql数据连接 spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=root #spring.datasource.max-active=20 #spring.datasource.max-idle=8 #spring.datasource.min-idle=8 #spring.datasource.initial-size=20 #mybatis 配置 # 配置映射文件加载 mybatis.mapper-locations=classpath*:mapper/*.xml # 实体类通过别名使用 #mybatis.type-aliases-package=com.example.springboot.mybatis.entity编写实体类
package com.example.springboot.mybatis.entity; public class User { private String id; private String username; private String password; private String email; /** * 是否可用(0禁用,1可用) */ private Integer useable; /** * 创建时间 */ private String addtime; /** * 登陆时间 */ private String logintime; /** * 登陆IP */ private String loginip;
编写dao类
package com.example.springboot.mybatis.dao; import com.example.springboot.mybatis.entity.User; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * 基于接口编程,通过mybatis与spring整合注入,在xml中编写sql语句 */ @Mapper public interface UserMapper { List<User> queryList(); void save(User user); void batchDelete(Integer[] ids); void update(User user); }
编写dao对应xml配置文件
创建src/main/resources/mapper/UserMapper.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.example.springboot.mybatis.dao.UserMapper"> <select id="queryList" resultType="com.example.springboot.mybatis.entity.User"> SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u </select> <select id="queryById" resultType="com.example.springboot.mybatis.entity.User"> SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u where u.id = #{id} </select> <insert id="save"> insert into t_user(id,username, password, email, useable, addtime) values(#{id},#{username}, #{password}, #{email}, #{useable}, now()) </insert> <update id="update"> update t_user set password = #{password}, email = #{email}, useable = #{useable} where id = #{id} </update> <delete id="batchDelete"> delete from m_user where id in <foreach collection="array" item="item" open="(" separator="," close=")"> #{item} </foreach> </delete> <!-- <delete id="delUsers"> delete from m_user where id in <foreach collection="list" item="item" open="(" separator="," close=")"> #{item} </foreach> </delete> --> </mapper>
编写service类
package com.example.springboot.mybatis.service; import com.example.springboot.mybatis.dao.UserMapper; import com.example.springboot.mybatis.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @desc 通过mybatis xml配置文件读取数据 * @Author wangsh * @date 2018/5/5 23:12 * @return */ @Service public class UserService2 { @Autowired private UserMapper userMapper; public List<User> queryList() { List<User> queryList = userMapper.queryList(); return queryList; } public void batchDelete(Integer[] ids) { userMapper.batchDelete(ids); } // REQUIRED:表示必须又事物管理,如果没有事物,就创建一个事物 @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class) public void update(User user) { userMapper.update(user); } // REQUIRED:表示必须又事物管理,如果没有事物,就创建一个事物 @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class) public void save(User user) { userMapper.save(user); } }
编写controller类
package com.example.springboot.mybatis.web; import com.example.springboot.mybatis.entity.User; import com.example.springboot.mybatis.service.UserService; import com.example.springboot.mybatis.service.UserService2; import com.example.springboot.mybatis.util.UUIDUtil; import com.github.pagehelper.PageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @desc mybatis 操作数据库查询示例 * @Author wangsh * @date 2018/5/5 23:18 * @return */ @RestController @RequestMapping("/user") public class UserController { /** * 通过mybatis xml配置文件读取数据 */ @Autowired private UserService2 userService2; @RequestMapping("/queryList2") @ResponseBody public List<User> queryList() { List<User> queryList = userService2.queryList(); return queryList; } @RequestMapping("/save2") @ResponseBody public User save2() { User user = new User(); user.setId(UUIDUtil.getUUID()); user.setUsername("lisi"); user.setPassword("lisi"); userService2.save(user); return user; } }编写启动服务类
package com.example.springboot.mybatis; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * @desc mybatis启动服务 * @Author wangsh * @date 2018/5/5 23:20 * @return */ @SpringBootApplication //如果mybatis中service实现类中加入@Transaction事务注解,需要此处添加该注解 @EnableTransactionManagement //扫描的是mapper.xml中namespace指向值的包位置 @MapperScan("com.example.*") public class SpringbootMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMybatisApplication.class, args); } }
启动服务测试
浏览器输入: http://localhost:8080//user/queryList2