本博文主要讲解spring boot项目整合MyBatis
1.最终项目结构图
2.文件清单
清单: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</groupId>
<artifactId>demo-springboot-MyBatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo-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.1.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>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<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>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
清单:User.java
package com.example.pojo;
public class User {
private Long id;
private String userName;
private String userSex;
private int userAge;
public User() {
}
public User(String userName, String userSex, int userAge) {
super();
this.userName = userName;
this.userSex = userSex;
this.userAge = userAge;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
}
清单:UserMapper.java
package com.example.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.example.pojo.User;
public interface UserMapper {
/**
* 查询所有用户信息
*
* @return
*/
@Select("select * from user")
@Results(value = { @Result(property = "userSex", column = "user_sex", javaType = String.class),
@Result(property = "userName", column = "user_name"), @Result(property = "userAge", column = "user_age") })
List<User> findList();
/**
* 通过ID查询
*
* @param id
* @return
*/
@Select("select * from user u where u.id=#{id}")
User findOne(@Param("id") Long id);
/**
* 新增一个
*
* @param user
*/
@Insert("insert into user (user_name,user_sex,user_age) values(#{userName},#{userSex},#{userAge})")
void insert(User user);
/**
* 修改
*
* @param user
*/
@Update("update user u set u.user_name=#{userName},u.user_sex=#{userSex},u.user_age=#{userAge} where u.id=#{id}")
void update(User user);
/**
* 删除
*
* @param id
*/
@Delete("delete from user where id=#{id}")
void delete(@Param("id") Long id);
}
清单:UserController.java
package com.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
/**
* index
*
* @return
*/
@RequestMapping("/")
public String index() {
return "User Info By MyBatis";
}
@RequestMapping("/user/list.json")
public Object allUsers() {
List<User> users = userMapper.findList();
return users;
}
}
清单:Application.java
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@MapperScan(basePackages = { "com.example.mapper" }) // 自动扫描mapper
@EnableTransactionManagement//启用事物管理,在service上使用@Transactional(注意是spring的 注解)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
清单:application.properties
#==================DataSource Config Start==================
#name
#spring.datasource.name=test
#url
#spring.datasource.url=jdbc:sqlserver://192.168.xxx.xxx;instanceName=sql_03;DatabaseName=edu;integratedSecurity=false
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
#DriverClass
#spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#DB username
spring.datasource.username=root
#DB password
spring.datasource.password=root
#==================DataSource Config End==================
#==================MyBatis Config Start==================
#ORM Bean Package
mybatis.type-aliases-package=com.example.pojo
mybatis.mapper-locations=classpath:/mapper/*.xml
#打印MyBatisSql语句
logging.level.com.example.mapper=DEBUG
#==================MyBatis Config End ==================
清单:UserMapperTest.java
package com.example.test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
// @Test
public void testInsert() {
try {
userMapper.insert(new User("xqlee1", "男", 26));
userMapper.insert(new User("xqlee2", "男", 23));
userMapper.insert(new User("xqlee3", "男", 27));
} catch (Exception e) {
e.printStackTrace();
}
}
// @Test
public void testUpdate() {
try {
User user = new User("测试0000", "男", 23);
user.setId(1l);
userMapper.update(user);
} catch (Exception e) {
e.printStackTrace();
}
}
//@Test
public void testQuery() {
try {
List<User> users=userMapper.findList();
for(User u:users){
System.out.println("ID:"+u.getId()+" Name:"+u.getUserName()+" Sex:"+u.getUserSex()+" Age:"+u.getUserAge());
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testDelete(){
try {
userMapper.delete(1l);
testQuery();
} catch (Exception e) {
e.printStackTrace();
}
}
}
https://www.leftso.com/article/80.html