这是一个学习MyBatis做点项目(Springboot+MyBatis+Maven),仅供自己做学习参考。
结构目录如图
创建项目的步骤如下图
Java版本要一致,我用的是Java1.8
这里我用了Lombok插件,然后项目就建好了。
代码详细实现如下
一些配置文件
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.liu2</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo2</name>
<description>Demo project for Spring Boot</description>
<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-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
server:
port: 8080
spring:
datasource:
username: root
password: root
# url地址不一样,我用的不是本地MySQL,是阿里云的服务器存储
url: jdbc:mysql://localhost:3306/mybaticdemo?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.liu2.entity
logging:
level:
com:
example:
mapper: debug
实体类
User.java
package com.liu2.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.Alias;
import java.io.Serializable;
/**
* @author Administrator
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Alias(value = "User")
public class User implements Serializable {
private static final long serialVersionUID = -6613686341202168918L;
/**
*
*/
private Integer id;
private String name;
private String password;
private String sex;
private Integer age;
private People people;
}
People.java
package com.liu2.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.Alias;
import java.io.Serializable;
import java.util.List;
/**
* @author Administrator
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Alias(value = "People")
public class People implements Serializable {
private static final long serialVersionUID = 6507825290007954789L;
private String name;
private String address;
private String city;
private List<User> users;
}
UserPeople.java
package com.liu2.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.Alias;
import java.io.Serializable;
/**
* @author Administrator
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Alias(value = "UserPeople")
public class UserPeople implements Serializable {
private static final long serialVersionUID = -5833349907084967817L;
private Integer id;
private String name;
private String password;
private String sex;
private Integer age;
private String address;
private String city;
}
Controller层
UserController.java
package com.liu2.controller;
import com.liu2.entity.People;
import com.liu2.entity.User;
import com.liu2.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author Administrator
*/
@Slf4j(topic = "UserController")
@RestController
@ResponseBody
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUser")
public String findUser(Integer id) {
if(userService.findUser(id)==null){
return "查无此人!";
}
return userService.findUser(id).toString();
}
@GetMapping("/getAllUser")
public List<User> findAllUser(@RequestParam String name) {
return userService.findAllUser(name);
}
@GetMapping("/getAll")
public List<String> getAllName() {
return userService.getAllName();
}
@PostMapping(value = "/addUser")
public String addUser(@RequestBody User user){
try {
userService.addUser(user);
return "添加成功!";
} catch (Exception e) {
log.error("添加失败",e);
return "添加失败!";
}
}
@DeleteMapping("/deleteUser")
public String deleteUser(@RequestParam(value = "age",required = false,defaultValue = "18") Integer age){
try {
userService.deleteUser(age);
return "删除成功!";
} catch (Exception e) {
log.error("删除失败",e);
return "删除失败!";
}
}
@PostMapping(value = "/updateUser")
public String updateUser(@RequestBody User user){
try {
userService.updateUser(user);
return "修改成功!";
} catch (Exception e) {
log.error("修改失败",e);
return "修改失败!";
}
}
@GetMapping("/getUserByLastName")
public String getUserByLastName(String lastName){
List<User> users = userService.getUserByLastName(lastName);
if (CollectionUtils.isEmpty(users)) {
return "查无此人!";
}
return userService.getUserByLastName(lastName).toString();
}
@GetMapping("/getUser1")
public String getUser1(String name){
List<User> users=userService.getUser1(name);
if (CollectionUtils.isEmpty(users)){
return "查无此人!";
}else {
return userService.getUser1(name).toString();
}
}
@GetMapping("/getUser2")
public String getUser2(String name){
List<People> people=userService.getUser2(name);
if (CollectionUtils.isEmpty(people)){
return "查无此人!";
}else {
return userService.getUser2(name).toString();
}
}
}
UserPeopleController.java
package com.liu2.controller;
import com.liu2.entity.UserPeople;
import com.liu2.service.UserPeopleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author Administrator
*/
@Slf4j(topic="UserPeopleController")
@RestController
public class UserPeopleController {
@Autowired
private UserPeopleService userPeopleService;
@GetMapping("/getUserPeople")
public List<UserPeople> getUserPeople(Integer id){
return userPeopleService.getUserPeople(id);
}
@GetMapping("/getUserPeople2")
public List<UserPeople> getUserPeople2(String city){
return userPeopleService.getUserPeople2(city);
}
}
Service层
UserService.java接口
package com.liu2.service;
import com.liu2.entity.People;
import com.liu2.entity.User;
import java.util.List;
/**
* @author Administrator
*/
public interface UserService {
User findUser(Integer id);
List<User> findAllUser(String name);
List<String> getAllName();
int addUser(User user);
int deleteUser(Integer age);//删除年龄大于50的
int updateUser(User user);
List<User> getUserByLastName(String lastName);
List<User> getUser1(String name);
List<People> getUser2(String name);
}
UserPeopleService.java接口
package com.liu2.service;
import com.liu2.entity.UserPeople;
import java.util.List;
/**
* @author Administrator
*/
public interface UserPeopleService {
/**
*user表和people表连接,查询符合id的userpeople
* @param id
* @return
*/
List<UserPeople> getUserPeople(Integer id);
/**
* 按city查询信息
* @param city
* @return
*/
List<UserPeople> getUserPeople2(String city);
}
UserServiceImpl.java接口的实现
package com.liu2.service.impl;
import com.liu2.entity.People;
import com.liu2.entity.User;
import com.liu2.mapper.UserMapper;
import com.liu2.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findUser(Integer id){
return userMapper.findUser(id);
}
@Override
public List<User> findAllUser(String name){
return userMapper.findAllUser(name);
}
@Override
public List<String> getAllName(){
return userMapper.getAllName();
}
@Override
public int addUser(User user){
return userMapper.addUser(user);
}
@Override
public int deleteUser(Integer age){
return userMapper.deleteUser(age);
}
@Override
public int updateUser(User user){
return userMapper.updateUser(user);
}
@Override
public List<User> getUserByLastName(String lastName){
return userMapper.getUserByLastName(lastName);
}
@Override
public List<User> getUser1(String name){
return userMapper.getUser1(name);
}
@Override
public List<People> getUser2(@Param(value = "name") String name){
return userMapper.getUser2(name);
}
}
UserPeopleServiceImpl.java接口实现
package com.liu2.service.impl;
import com.liu2.entity.UserPeople;
import com.liu2.mapper.UserPeopleMapper;
import com.liu2.service.UserPeopleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Administrator
*/
@Service
public class UserPeopleServiceImpl implements UserPeopleService {
@Autowired
private UserPeopleMapper userPeopleMapper;
@Override
public List<UserPeople> getUserPeople(Integer id){
return userPeopleMapper.getUserPeople(id);
}
@Override
public List<UserPeople> getUserPeople2(String city){
return userPeopleMapper.getUserPeople2(city);
}
}
Mapper层
UserMapper.java
package com.liu2.mapper;
import com.liu2.entity.People;
import com.liu2.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author Administrator
*/
@Repository
public interface UserMapper {
/**
* 按id查user
* @param id
* @return
*/
User findUser(Integer id);
/**
*按name查user
* @param name
* @return
*/
List<User> findAllUser(String name);
/**
* 查询所有name
* @return
*/
List<String> getAllName();
/**
* 添加user
* @param user
* @return
*/
int addUser(User user);
/**
* 删除age大于某个值的user
* @param age
* @return
*/
int deleteUser(Integer age);//删除年龄大于50的
/**
* 修改名叫name的user的age
* @param user
* @return
*/
int updateUser(User user);
/**
* 按姓名中的字段模糊查找user
* @param lastName
* @return
*/
List<User> getUserByLastName(String lastName);
/**
* 按name查询所有账号和地址等
* @param name
* @return
*/
List<User> getUser1(@Param(value = "name") String name);
List<People> getUser2(@Param(value = "name") String name);
}
UserPeopleMapper.java
package com.liu2.mapper;
import com.liu2.entity.UserPeople;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author Administrator
*/
@Repository
public interface UserPeopleMapper {
/**
*user表和people表连接,查询符合id的userpeople
* @param id
* @return
*/
List<UserPeople> getUserPeople(Integer id);
/**
*按city查询信息
* @param city
* @return
*/
List<UserPeople> getUserPeople2(String city);
}
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.liu2.mapper.UserMapper">
<select id="findUser" resultType="User">
select *
from user
where id = #{id}
</select>
<select id="findAllUser" resultType="User">
select *
from user
where name = #{name}
</select>
<select id="getAllName" resultType="String">
select name
from user
limit 2,3
</select>
<insert id="addUser" parameterType="User">
insert
into user(id,name,password,age,sex)
values(#{id} ,#{name},#{password},#{age},#{sex})
</insert>
<delete id="deleteUser" parameterType="User">
delete
from user
where age>#{age}
</delete>
<update id="updateUser" parameterType="User">
update user
set age = #{age}
where name=#{name}
</update>
<select id="getUserByLastName" parameterType="String" resultType="User">
select *
from user
where name like concat ('%',#{lastName},'%')
</select>
<select id="getUser1" resultMap="GetUser">
SELECT u.id,u.name, u.age,u.sex,p.city
FROM user u LEFT JOIN people p ON u.NAME = p.NAME
<where>
<if test="name !=null and name != '' ">
and p.name = #{name}
</if>
</where>
</select>
<resultMap id="GetUser" type="User">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<association property="people" javaType="People">
<result property="name" column="name"></result>
<result property="city" column="city"></result>
</association>
</resultMap>
<select id="getUser2" resultMap="GetUser2">
select p.name,p.city,u.password,u.age as age,u.sex
from user u left join people p on u.name = p.name
<where>
<if test="name !=null">
and u.name=#{name}
</if>
</where>
</select>
<resultMap id="GetUser2" type="People">
<result property="name" column="name"></result>
<result property="city" column="city"></result>
<collection property="users" ofType="User">
<result property="name" column="name"></result>
<result property="password" column="password"></result>
<result property="sex" column="sex"></result>
<result property="age" column="age"></result>
</collection>
</resultMap>
</mapper>
UserPeopleMapper.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.liu2.mapper.UserPeopleMapper">
<select id="getUserPeople" resultType="UserPeople">
select *
from user u left join people p on u.name=p.pname
where u.id = #{id}
</select>
<select id="getUserPeople2" resultType="UserPeople">
select *
from user u left join people p on u.name=p.pname
where p.city = #{city}
</select>
</mapper>
实现类
DemoApplication.java
package com.liu2;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author Administrator
*/
@MapperScan(basePackages = "com.liu2.mapper")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}