springboot 은 Mybatis(xml 와 주석)를 사용 하 는 과정 을 모두 해석 합 니 다.

13043 단어 springbootmybatis
갓 졸업 한 첫 번 째 업 무 는 자바 개발 입 니 다.프로젝트 에 my batis 를 사용 해 야 합 니 다.이 기록 학습 과정 은 간단 한 demo 일 뿐 입 니 다.my batis 용법 은 모두 쓸 수 없습니다.더욱 복잡 한 수요 가 있 으 면 my batis 의 공식 중국어 문 서 를 보 는 것 을 권장 합 니 다.클릭 하여 점프.다음 시 프로젝트 환경/버 전.
•개발 도구:IDEA
•jdk 버 전:1.8
•springboot 버 전:2.03
기타 의존 버 전 은 아래 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>mybatis-test</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 <name>mybatis-test</name>
 <description>Demo project for Spring Boot</description>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.3.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-web</artifactId>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
  </dependency>
  <!--mybatis   -->
  <dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.3.2</version>
  </dependency>
  <!--alibaba     -->
  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.9</version>
  </dependency>
  <!--    -->
  <dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper-spring-boot-starter</artifactId>
   <version>1.2.5</version>
  </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>
1.항목 만 들 기
아이디어 의 spring initializr 를 사용 하여 maven 프로젝트 를 생 성 합 니 다.프로젝트 명령 은 my batis-test 입 니 다.웹,my sql,my batis 의존 을 선택 하면 성공 할 수 있 습 니 다.(상세 한 과정 은 군더더기 없 이 springboot 생 성 과정 을 배 워 야 할 경우 이 글 을 참고 하 시기 바 랍 니 다.
그리고 위의 pom 파일 에 따라 부족 한 의존 도 를 보완 합 니 다.이 어 패키지 enity,service,my batis 맵 폴 더 mapper 를 만 들 고 만 듭 니 다.편리 한 설정 을 위해 application.properties 를 application.yml 로 변경 합 니 다.REST 인터페이스 가 있 기 때문에 static 과 templates 디 렉 터 리 가 필요 없습니다.수정 이 끝 난 후의 항목 구 조 는 다음 과 같다.

프로젝트 구조
시작 클래스 를 수정 하고@MapperScan("com.example.my batistest.dao")을 추가 하여 dao 디 렉 터 리 를 자동 으로 검색 하여 모든 dao 가@Mapper 주 해 를 수 동 으로 추가 하지 않도록 합 니 다.코드 는 다음 과 같 습 니 다:

@SpringBootApplication
@MapperScan("com.example.mybatistest.dao")
public class MybatisTestApplication {
 public static void main(String[] args) {
  SpringApplication.run(MybatisTestApplication.class, args);
 }
}
application.yml,설정 항목 을 수정 합 니 다.코드 는 다음 과 같 습 니 다.

mybatis:
 #       
 type-aliases-package: com.example.mybatistest.entity
 #  mapper      
 mapper-locations: classpath:mapper/*.xml
#pagehelper      
pagehelper:
 helper-dialect: mysql
 reasonable: true
 support-methods-arguments: true
 params: count=countSql
 returnPageInfo: check
server:
 port: 8081
spring:
 datasource:
 name: mysqlTest
 type: com.alibaba.druid.pool.DruidDataSource
 #druid       
 druid:
  #       filters
  filters: stat
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true
  username: root
  password: 123456
  #       ,  ,  
  initial-size: 1
  min-idle: 1
  max-active: 20
  #          
  max-wait: 6000
  #                 
  time-between-eviction-runs-millis: 60000
  #              
  min-evictable-idle-time-millis: 300000
  #  PSCache,        PSCache   。oracle   true,mysql   false。            
  pool-prepared-statements: false
  max-pool-prepared-statement-per-connection-size: 20
 http:
 encoding:
  charset: utf-8
  enabled: true
2.코드 작성
먼저 데이터 시트 를 만 듭 니 다.sql 문 구 는 다음 과 같 습 니 다.

CREATE TABLE `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) NOT NULL,
 `age` tinyint(4) NOT NULL DEFAULT '0',
 `password` varchar(255) NOT NULL DEFAULT '123456',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
 그리고 entity 패키지 에 실체 클래스 User.java 를 만 듭 니 다.

public class User {
 private int id;
 private String name;
 private int age;
 private String password;
 public User(int id, String name, int age, String password) {
  this.id = id;
  this.name = name;
  this.age = age;
  this.password = password;
 }
 public User(){}
 //getter setter    
}
dao 패키지 아래 UserDao.java 만 들 기

public interface UserDao {
 //    
 int insert(User user);
 //  id  
 User selectById(String id);
 //    
 List<User> selectAll();
}
mapper 폴 더 에 UserMapper.xml 를 만 들 고 구체 적 인 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.mybatistest.dao.UserDao">
 <sql id="BASE_TABLE">
  user
 </sql>
 <sql id="BASE_COLUMN">
  id,name,age,password
 </sql>
 <insert id="insert" parameterType="com.example.mybatistest.entity.User" useGeneratedKeys="true" keyProperty="id">
  INSERT INTO <include refid="BASE_TABLE"/>
  <trim prefix="(" suffix=")" suffixOverrides=",">
   name,password,
   <if test="age!=null">
    age
   </if>
  </trim>
  <trim prefix=" VALUE(" suffix=")" suffixOverrides=",">
   #{name,jdbcType=VARCHAR},#{password},
   <if test="age!=null">
    #{age}
   </if>
  </trim>
 </insert>
 <select id="selectById" resultType="com.example.mybatistest.entity.User">
  select
   <include refid="BASE_COLUMN"/>
  from
   <include refid="BASE_TABLE"/>
  where id=#{id}
 </select>
 <select id="selectAll" resultType="com.example.mybatistest.entity.User">
  select
   <include refid="BASE_COLUMN"/>
  from
   <include refid="BASE_TABLE"/>
 </select>
</mapper>
이로써 my batis 코드 를 사용 하여 작성 한 후,사용 할 때 dao 인터페이스 에 있 는 방법 을 호출 하면 됩 니 다.
3.테스트
우 리 는 service,contrller 를 작성 한 후에 postman 을 사용 하여 테스트 를 진행 합 니 다.
먼저 UserService.java 를 작성 합 니 다.코드 는 다음 과 같 습 니 다.

@Component
public class UserService {
 @Autowired
 private UserDao userDao;
 public User getByUserId(String id){
  return userDao.selectById(id);
 }
 //      
 public List<User> getAll(){
  return userDao.selectAll();
 }
 //    
 public PageInfo<User> getAll(int pageNum,int pageSize){
  PageHelper.startPage(pageNum,pageSize);
  List<User> users = userDao.selectAll();
  System.out.println(users.size());
  PageInfo<User> result = new PageInfo<>(users);
  return result;
 }
 public int insert(User user){
  return userDao.insert(user);
 }
}
UserController.java 작성

@RestController
public class UserController {
 @Autowired
 private UserService userService;
 @GetMapping("/user/{userId}")
 public User getUser(@PathVariable String userId){
  return userService.getByUserId(userId);
 }
 @GetMapping("/user")
 public List<User> getAll(){
  return userService.getAll();
 }
 @GetMapping("/user/page/{pageNum}")
 public Object getPage(@PathVariable int pageNum,
       @RequestParam(name = "pageSize",required = false,defaultValue = "10") int pageSize){
  return userService.getAll(pageNum,pageSize);
 }
 @PostMapping("/user")
 public Object addOne(User user){
  userService.insert(user);
  return user;
 }
}
프로젝트 를 시작 하고 postman 을 통 해 테스트 를 요청 합 니 다.테스트 결 과 는 다음 과 같 습 니 다.
•데이터 삽입:

•조회 데이터

페이지 별 조회

4.주석 작성 sql
위 에서 사용 하 는 것 은 xml 방식 으로 sql 코드 를 작성 하 는 것 입 니 다.사실 my batis 도 주석 에서 sql 을 작성 하 는 것 을 지원 합 니 다.복잡 한 xml 조회 파일 을 만 드 는 것 을 피 할 수 있 지만 sql 문 구 를 코드 에 결합 시 켜 복잡 한 조 회 를 실현 하기 어렵 기 때문에 간단 한 sql 문 구 를 작성 하 는 데 도 많이 사 용 됩 니 다.
주 해 를 사용 하려 면 먼저 application.yml 설정 파일 의 mapper-locations:classpath:mapper/*.xml 를 주석 합 니 다.그리고 UserDao.java 에 sql 주 해 를 추가 합 니 다.코드 는 다음 과 같 습 니 다.

public interface UserDao {
 //    
 @Insert("insert into user(name,age,password) value(#{name},#{age},#{password})")
 @Options(useGeneratedKeys=true,keyColumn="id",keyProperty="id")
 int insert(User user);
 //  id  
 @Select("select * from user where id=#{id}")
 User selectById(String id);
 //    
 @Select("select * from user")
 List<User> selectAll();
}
그리고 프로젝트 테스트 를 다시 시작 하면 테스트 결 과 는 위 와 똑 같 습 니 다.
본 고 는 오리지널 로 https://www.tapme.top/blog/detail/2018-09-01-10-38 에 발표 되 었 다.
원본 주소:https://github.com/FleyX/demo-project/tree/master/mybatis-test.

좋은 웹페이지 즐겨찾기