Springboot Mybatis

<?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>org.example</groupId>
<artifactId>soringbootdo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<artifactId>spring-boot-starter-web</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.2.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
</project>

2.实体类

package com.southwind.entity;

import lombok.Data;

@Data
public class User {
private Integer id;
private String name;
private Integer money;
}

3.创建Repository

package com.southwind.mybatis.Repository;

import com.southwind.entity.User;

import java.util.List;

public interface UserRepository {
public List<User> findAll();
public User finById(Integer id);
public int save (User user);
public int update(User user);
public int delete(Integer id);
}
<?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.southwind.mybatis.Repository.UserRepository">
<select id="findAll" resultType="User">
select * from people
</select> <select id="finById" parameterType="java.lang.Integer" resultType="User">
select * from people where id=#{id}
</select> <insert id="save" parameterType="User">
insert into people(id,name,money) values(#{id},#{name},#{money})
</insert> <update id="update" parameterType="User">
update people set name=#{name},money=#{name} where id=#{id}
</update> <delete id="delete" parameterType="java.lang.Integer">
delete from people where id=#{id}
</delete>
</mapper>

4.Hnadelri

package com.southwind.Controller;

import com.southwind.entity.User;
import com.southwind.mybatis.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import java.util.List; @Controller
@RequestMapping("mbuser")
public class MuserHandler {
@Autowired
private UserRepository userRepository; @GetMapping("/findall")
@ResponseBody
public List<User> findall(){
return userRepository.findAll();
} @GetMapping("/findbyid/{id}")
@ResponseBody
public User findbyid(@PathVariable("id")Integer id) {
return userRepository.finById(id);
} @PostMapping("/save")
@ResponseBody
public int save(@RequestBody User user){
return userRepository.save(user);
}
@PutMapping("/update")
@ResponseBody
public int update(@RequestBody User user){
return userRepository.update(user);
}
@DeleteMapping("/delete/{id}")
@ResponseBody
public int delete(@PathVariable Integer id){
return userRepository.delete(id);
}
}

5.配置文件:

spring:
datasource:
url: jdbc:mysql://localhost:3306/text?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
mybatis:
mapper-locations: classpath:/mapping/*.xml
type-aliases-package: com.southwind.entity

6.启动类

package com.southwind;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("com.southwind.mybatis.Repository")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}

Springboot 整合 Spring Data JPA

Spring Data JPA是Spring Data大家族的一员

JPA和Spring Data JPA的关系

JPA(Java Persistence API)java持久层的约束,定义了一系列的ORM接口,他本身不能直接使用,接口的必须实现才能使用,Hibernate框架实现了JPA规范的框架

Spring Data JPA是Spring框架提供的对JPA规范的抽象,通过约定的命名规范完成持久层接口的编写,在不需要实现接口的情况下,就可以完成对数据库的操作。

简单理解,通过Spring Data JPA只需要定义接口而不需要实现,就能完成CRUD操作

Spring Data JPA本身并不是一个具体的实现,他只是一个抽象层,底层还是需要Hibernate这样的JPA来提供支持。

Spring Data JPA和Spring JDBC Template的关系

JDBC Template是spring自带的一个JDBC的模版组件,底层实现了对JDBC的封装,用法和Mybatis类似,需要开发者定义SQL语句,JDBC Template帮助我们完成数据库的连接,SQL的执行,结果集的封装

Spring Data JPA是JPA的抽象

1.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>org.example</groupId>
<artifactId>soringbootdo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<artifactId>spring-boot-starter-web</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.2.4.RELEASE</version>
</parent>
<dependencies>
<!-- -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot 集成jdbcTenplate-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- springboot 集成Mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- springboot 集成JPA-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
</project>

2.实体类:完成实体类于表的映射

package com.southwind.entity;

import lombok.Data;

import javax.persistence.*;

@Data
@Entity(name = "people")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String name;
@Column
private Integer money;
}
  • @Entity将实体类与数据表进行映射
  • @Id将实体类中的成员变量于数据表的主键进行映射,一般是id
  • @GeneratedValue(strategy = GenerationType.IDENTITY)自动生成主键,strategy为主键选择的生成策略
  • @Column将实体类中的成员变量与数据表的普通字段进行映射

3.创建Repository

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package org.springframework.data.jpa.repository; import java.util.List;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor; @NoRepositoryBean
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
List<T> findAll(); List<T> findAll(Sort var1); List<T> findAllById(Iterable<ID> var1); <S extends T> List<S> saveAll(Iterable<S> var1); void flush(); <S extends T> S saveAndFlush(S var1); void deleteInBatch(Iterable<T> var1); void deleteAllInBatch(); T getOne(ID var1); <S extends T> List<S> findAll(Example<S> var1); <S extends T> List<S> findAll(Example<S> var1, Sort var2);
}
package com.southwind.mybatis.Repository;

import com.southwind.entity.User;
import org.springframework.data.jpa.repository.JpaRepository; public interface JpaUserRepository extends JpaRepository<User,Integer> {
}

4.创建Handler

package com.southwind.Controller;

import com.southwind.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.*; import java.util.List; @RestController("/jpaHandler")
@RequestMapping("/JpaUser")
public class JpaUserHandler {
@Autowired
private JpaRepository jpaRepository;
@GetMapping("/findall")
public List<User> findall(){
return jpaRepository.findAll();
} @GetMapping("/findbyid/{id}")
@ResponseBody
public User findbyid(@PathVariable("id")Integer id) {
return (User) jpaRepository.findById(id).get();
} @PostMapping("/save")
@ResponseBody
public void save(@RequestBody User user){
jpaRepository.save(user);
}
@PutMapping("/update")
@ResponseBody
public Object update(@RequestBody User user){
return jpaRepository.save(user);
}
@DeleteMapping("/delete/{id}")
@ResponseBody
public void delete(@PathVariable("id") Integer id){
jpaRepository.deleteById(id);
}
}

5.配置application.yml

spring:
datasource:
url: jdbc:mysql://localhost:3306/text?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
jpa:
show-sql: true
properties:
hibernate:
format_sql: true
mybatis:
mapper-locations: classpath:/mapping/*.xml
type-aliases-package: com.southwind.entity

6.在继承员原来的基础上增加新的方法

package com.southwind.jpa.Repository;

import com.southwind.entity.User;
import org.springframework.data.jpa.repository.JpaRepository; public interface JpaUserRepository extends JpaRepository<User,Integer> {
public User findByName(String name);
}

最新文章

  1. MySQL问题记录--Can&#39;t connect to MySQL server on localhost (10061)解决方法
  2. (int)、int.Parse()、int.TryParse()和Convert.ToInt32()的区别
  3. 【Windows批处理II】类C语言的学习和思考
  4. 在线头像上传(js)
  5. Coursera台大机器学习课程笔记9 -- Logistic Regression
  6. UVa 10007 - Count the Trees(卡特兰数+阶乘+大数)
  7. CUBRID学习笔记 3 net连接数据库并使用cubrid教程示例
  8. bzoj 2186: [Sdoi2008]沙拉公主的困惑
  9. sql 2000 &quot;无法执行查询,因为一些文件缺少或未注册&quot;的
  10. 移动端地图技术分享-- 百度高德SDK
  11. mock.js的真实数据模拟
  12. audio session config
  13. MySQL数据库8.0.15 安装教程
  14. DSAPI多功能组件编程应用-文件类
  15. 为何放弃Eclipse,选择IntelliJ IDEA,看完终于明白了
  16. Scala进阶之路-反射(reflect)技术详解
  17. MySQL事务(二)
  18. css3中的BFC,IFC,GFC和FFC
  19. 基于Disruptor并发框架的分类任务并发
  20. java基础学习总结——哈希编码

热门文章

  1. java中的自动拆装箱
  2. 【collection】1.java容器之HashMap&amp;LinkedHashMap&amp;Hashtable
  3. MapStruct与lombok加载顺序问题与annotationProcessorPaths的关系?
  4. 所元素设为border-box
  5. Scrum敏捷开发方法实践
  6. STM32标准库中GPIO_ReadInputData与GPIO_ReadInputDataBit的区别
  7. f-strings: Python字符串处理的瑞士军刀
  8. django.core.exceptions.ImproperlyConfigured: Application labels aren&#39;t unique, duplicates: rest_framework_swagger
  9. Linux第四章 进程
  10. PRIx64:uint64_t类型输出为十六进制格式