spring boot+mybatis整合
LZ 今天自己搭建了下 Spring boot+Mybatis,比原来的 Spring+SpringMVC+Mybatis 简单好多。其实只用 Spring boot 也可以开发,但是对于多表多条件分页查询,Spring boot 就有点力不从心了,所以 LZ 把 Mybatis 整合进去,不得不说,现在的框架搭建真的是方便。话不多说,进入正题。
一、java web 开发环境搭建
网上有很多教程,参考教程:http://www.cnblogs.com/Leo_wl/p/4752875.html
二、Spring boot 搭建
1、Intellij idea 菜单栏 File->new->project。
2、选择左侧栏中 spring initializr,右侧选择 jdk 版本,以及默认的 Service URL,点击 next。
/3、然后填写项目的 Group、Artifact 等信息,helloworld 阶段选默认就可以了,点击 next。
4、左侧点击 Web,中间一侧选择 Web,然后左侧选择 SQL,中间一侧选择 JPA、Mybatis、MYSQL(LZ 数据库用的是 mysql,大家可以选择其他 DB),点击 next。
5、填写 Project name 等信息,然后点击 Finish。
至此,一个 maven web 项目就创建好了,目录结构如下:
这样,Spring boot 就搭建好了,pom.xml 里已经有了 Spring boot 的 jar 包,包括我们的 mysql 数据连接的 jar 包。Spring boot 内置了类似 tomcat 这样的中间件,所以,只要运行 DemoApplication 中的 main 方法就可以启动项目了。我们测试一下。
在 src/main/java 下新建目录 com/demo/entity/User。
package com.demo.entity;public class User {
private String name;</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getName() { </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> name; } </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setName(String name) { </span><span style="color: rgba(0, 0, 255, 1)">this</span>.name =<span style="color: rgba(0, 0, 0, 1)"> name; }
}
相同目录下新建 com/demo/controller/TestBootController。
package com.demo.controller;import com.demo.entity.User;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@EnableAutoConfiguration
@RequestMapping("/testboot")
public class TestBootController {
@RequestMapping("getuser")
public User getUser() {
User user = new User();
user.setName("test");
return user;
}
}
spring boot 启动 DemoAplication 是需要扫描它下面的 Controller 等类的,所以将 DemoApplication 移动到 com/demo 目录下。还有就是 Spring boot 启动默认是要加载数据源的,所以我们在 src/main/resources 下新建 application.yml:
#默认使用配置
spring:
profiles:
active: dev
#公共配置与 profiles 选择无关
mybatis:
typeAliasesPackage: com.xdd.entity
mapperLocations: classpath:mapper/*.xml
#开发配置
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
或者将 pom.xml 中加载数据源的 jar 包先注释掉也可以。
/*<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>*/
最终的目录结构如下,
启动 DemoApplication 的 main 方法,访问 http://localhost:8080/testboot/getuser 即可。
三、整合 Mybatis
1、集成 druid,使用连接池。pom.xml 中添加:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.0</version> </dependency>
最终的 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.arm</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project <span style="color: rgba(0, 0, 255, 1)">for</span> Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.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.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
</project>
在 application.yml 中添加数据源、Mybatis 的实体和配置文件位置。
#默认使用配置
spring:
profiles:
active: dev
#公共配置与 profiles 选择无关 mapperLocations 指的路径是 src/main/resources
mybatis:
typeAliasesPackage: com.xdd.entity
mapperLocations: classpath:mapper/*.xml
#开发配置
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
# 使用 druid 数据源
type: com.alibaba.druid.pool.DruidDataSource
就这样就整合完成了!我们测试一下。
用 MyBatis Generator 自动生成代码,参考博文:http://blog.csdn.net/zhshulin/article/details/23912615 这里列一下自动生成的代码。
import com.xdd.entity.User; import org.springframework.stereotype.Component;public interface UserDao {
int deleteByPrimaryKey(Integer id);</span><span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> insert(User record); </span><span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> insertSelective(User record); User selectByPrimaryKey(Integer id); </span><span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> updateByPrimaryKeySelective(User record); </span><span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> updateByPrimaryKey(User record);
}
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.xdd.dao.UserDao" > <resultMap id="BaseResultMap" type="com.xdd.entity.User" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List" > id, user_name, password, age </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user_t where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from user_t where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.xdd.entity.User" > insert into user_t (id, user_name, password, age) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}) </insert> <insert id="insertSelective" parameterType="com.xdd.entity.User" > insert into user_t <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="userName != null" > user_name, </if> <if test="password != null" > password, </if> <if test="age != null" > age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="userName != null" > #{userName,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> <if test="age != null" > #{age,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.xdd.entity.User" > update user_t <set > <if test="userName != null" > user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if> <if test="age != null" > age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.xdd.entity.User" > update user_t set user_name = #{userName,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
public class User { private Integer id;</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> String userName; </span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> String password; </span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> Integer age; </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Integer getId() { </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> id; } </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setId(Integer id) { </span><span style="color: rgba(0, 0, 255, 1)">this</span>.id =<span style="color: rgba(0, 0, 0, 1)"> id; } </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getUserName() { </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> userName; } </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setUserName(String userName) { </span><span style="color: rgba(0, 0, 255, 1)">this</span>.userName = userName == <span style="color: rgba(0, 0, 255, 1)">null</span> ? <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)"> : userName.trim(); } </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getPassword() { </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> password; } </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setPassword(String password) { </span><span style="color: rgba(0, 0, 255, 1)">this</span>.password = password == <span style="color: rgba(0, 0, 255, 1)">null</span> ? <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)"> : password.trim(); } </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Integer getAge() { </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> age; } </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setAge(Integer age) { </span><span style="color: rgba(0, 0, 255, 1)">this</span>.age =<span style="color: rgba(0, 0, 0, 1)"> age; }
}
最后将 DemoApplication.java 修改一下,让其扫描 dao 层接口。
import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.support.SpringBootServletInitializer;@SpringBootApplication
@MapperScan("com.xdd.dao")
public class DemoApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
自己添加 controller 和 service
import java.util.List; import java.util.Map;public interface UserService {
public User getUserById(int userId);</span><span style="color: rgba(0, 0, 255, 1)">boolean</span><span style="color: rgba(0, 0, 0, 1)"> addUser(User record);
}
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.List;
import java.util.Map;@Service("userService")
public class UserServiceImpl implements UserService {@Resource </span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> UserDao userDao; </span><span style="color: rgba(0, 0, 255, 1)">public</span> User getUserById(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> userId) { </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> userDao.selectByPrimaryKey(userId); } </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">boolean</span><span style="color: rgba(0, 0, 0, 1)"> addUser(User record){ </span><span style="color: rgba(0, 0, 255, 1)">boolean</span> result = <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">; </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> { userDao.insertSelective(record); result </span>= <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">; } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception e) { e.printStackTrace(); } </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result; }
}
@Controller @RequestMapping("/user") public class UserController { @Resource private UserService userService;@RequestMapping(</span>"/showUser"<span style="color: rgba(0, 0, 0, 1)">) @ResponseBody </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> User toIndex(HttpServletRequest request, Model model){ </span><span style="color: rgba(0, 0, 255, 1)">int</span> userId = Integer.parseInt(request.getParameter("id"<span style="color: rgba(0, 0, 0, 1)">)); User user </span>= <span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.userService.getUserById(userId); </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> user; }
}
浏览器访问 http://localhost:8080/user/showUser?id=1
以前找别人的教程的时候总是嫌弃人家写的不详细,真的自己写的时候发现很多细节我也详细介绍不到,比如 yml 文件使用,比如数据库,看来还是要求别人容易,要求自己难。
-------------------------------------- 小程序试水 --------------------------------------