随笔 - 134,  文章 - 0,  评论 - 0,  阅读 - 21277

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);
}

posted on   Steam残酷  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示