日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring boot+mybatis整合

發(fā)布時(shí)間:2024/4/17 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring boot+mybatis整合 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

  LZ今天自己搭建了下Spring boot+Mybatis,比原來的Spring+SpringMVC+Mybatis簡(jiǎn)單好多。其實(shí)只用Spring boot也可以開發(fā),但是對(duì)于多表多條件分頁查詢,Spring boot就有點(diǎn)力不從心了,所以LZ把Mybatis整合進(jìn)去,不得不說,現(xiàn)在的框架搭建真的是方便。話不多說,進(jìn)入正題。

一、java web開發(fā)環(huán)境搭建

  網(wǎng)上有很多教程,參考教程:http://www.cnblogs.com/Leo_wl/p/4752875.html?

二、Spring boot搭建

  1、Intellij idea菜單欄File->new->project。

  

  2、選擇左側(cè)欄中spring initializr,右側(cè)選擇jdk版本,以及默認(rèn)的Service URL,點(diǎn)擊next。

  

  /3、然后填寫項(xiàng)目的Group、Artifact等信息,helloworld階段選默認(rèn)就可以了,點(diǎn)擊next。

  

  4、左側(cè)點(diǎn)擊Web,中間一側(cè)選擇Web,然后左側(cè)選擇SQL,中間一側(cè)選擇JPA、Mybatis、MYSQL(LZ數(shù)據(jù)庫用的是mysql,大家可以選擇其他DB),點(diǎn)擊next。

  

  5、填寫Project name 等信息,然后點(diǎn)擊Finish。

  

  至此,一個(gè)maven web項(xiàng)目就創(chuàng)建好了,目錄結(jié)構(gòu)如下:

  

這樣,Spring boot就搭建好了,pom.xml里已經(jīng)有了Spring boot的jar包,包括我們的mysql數(shù)據(jù)連接的jar包。Spring boot內(nèi)置了類似tomcat這樣的中間件,所以,只要運(yùn)行DemoApplication中的main方法就可以啟動(dòng)項(xiàng)目了。我們測(cè)試一下。

在src/main/java下新建目錄com/demo/entity/User。

package com.demo.entity;public class User {private String name;public String getName() {return name;}public void setName(String name) {this.name = 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啟動(dòng)DemoAplication是需要掃描它下面的Controller等類的,所以將DemoApplication移動(dòng)到com/demo目錄下。還有就是Spring boot啟動(dòng)默認(rèn)是要加載數(shù)據(jù)源的,所以我們?cè)趕rc/main/resources下新建application.yml:

#默認(rèn)使用配置 spring:profiles:active: dev#公共配置與profiles選擇無關(guān) mybatis:typeAliasesPackage: com.xdd.entitymapperLocations: classpath:mapper/*.xml---#開發(fā)配置 spring:profiles: devdatasource:url: jdbc:mysql://localhost:3306/testusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driver

  或者將pom.xml中加載數(shù)據(jù)源的jar包先注釋掉也可以。

/*<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.0</version> </dependency>*/

最終的目錄結(jié)構(gòu)如下,

啟動(dòng)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 for 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中添加數(shù)據(jù)源、Mybatis的實(shí)體和配置文件位置。

#默認(rèn)使用配置 spring:profiles:active: dev#公共配置與profiles選擇無關(guān) mapperLocations指的路徑是src/main/resources mybatis:typeAliasesPackage: com.xdd.entitymapperLocations: classpath:mapper/*.xml---#開發(fā)配置 spring:profiles: devdatasource:url: jdbc:mysql://localhost:3306/testusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driver# 使用druid數(shù)據(jù)源type: com.alibaba.druid.pool.DruidDataSource

就這樣就整合完成了!我們測(cè)試一下。

用MyBatis Generator自動(dòng)生成代碼,參考博文:http://blog.csdn.net/zhshulin/article/details/23912615?這里列一下自動(dòng)生成的代碼。

import com.xdd.entity.User; import org.springframework.stereotype.Component;public interface UserDao {int deleteByPrimaryKey(Integer id);int insert(User record);int insertSelective(User record);User selectByPrimaryKey(Integer id);int updateByPrimaryKeySelective(User record);int 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_twhere id = #{id,jdbcType=INTEGER}</select><delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >delete from user_twhere 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_tset 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;private String userName;private String password;private Integer age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName == null ? null : userName.trim();}public String getPassword() {return password;}public void setPassword(String password) {this.password = password == null ? null : password.trim();}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = 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);boolean 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 {@Resourceprivate UserDao userDao;public User getUserById(int userId) {return userDao.selectByPrimaryKey(userId);}public boolean addUser(User record){boolean result = false;try {userDao.insertSelective(record);result = true;} catch (Exception e) {e.printStackTrace();}return result;}}

?

@Controller @RequestMapping("/user") public class UserController {@Resourceprivate UserService userService;@RequestMapping("/showUser")@ResponseBodypublic User toIndex(HttpServletRequest request, Model model){int userId = Integer.parseInt(request.getParameter("id"));User user = this.userService.getUserById(userId);return user;}}

瀏覽器訪問http://localhost:8080/user/showUser?id=1

以前找別人的教程的時(shí)候總是嫌棄人家寫的不詳細(xì),真的自己寫的時(shí)候發(fā)現(xiàn)很多細(xì)節(jié)我也詳細(xì)介紹不到,比如yml文件使用,比如數(shù)據(jù)庫,看來還是要求別人容易,要求自己難。

--------------------------------------小程序試水--------------------------------------

轉(zhuǎn)載于:https://www.cnblogs.com/peterxiao/p/7779188.html

總結(jié)

以上是生活随笔為你收集整理的spring boot+mybatis整合的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。