批里批里 (゜-゜)つ🍺 干杯~|

七つ一旋桜

园龄:4年2个月粉丝:6关注:3

2022-09-07 22:34阅读: 511评论: 1推荐: 0

springboot 集成jimmer

java

添加依赖

<repositories>
    <repository>
        <id>nexus-tencentyun</id>
        <name>Nexus tencentyun</name>
        <url>http://mirrors.cloud.tencent.com/nexus/repository/maven-public/</url>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>nexus-tencentyun</id>
        <name>Nexus tencentyun</name>
        <url>http://mirrors.cloud.tencent.com/nexus/repository/maven-public/</url>
    </pluginRepository>
</pluginRepositories>

<properties>
    <java.version>1.8</java.version>
    <jimmer.version>0.8.114</jimmer.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.babyfish.jimmer</groupId>
        <artifactId>jimmer-spring-boot-starter</artifactId>
        <version>${jimmer.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.30</version>
    </dependency>
    ...
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.10.1</version>
            <configuration>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.babyfish.jimmer</groupId>
                        <artifactId>jimmer-apt</artifactId>
                        <version>${jimmer.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>

因为后续代码(配置类和业务代码等)需要使用到代码生成器生成的代码,因此需要先定义实体类

model

immutable: jimmer采用接口定义实体,而不是用类

import org.babyfish.jimmer.sql.*;

@Table(name = "t_user")
@Entity
public interface User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    long id();
	@Key
    String username();
    String password();
    Boolean sex();
}

定义spec
src/main/dto/com/example/demo/model路径下创建TUser.dto

export com.example.demo.model.TUser
    -> package com.example.demo.model.dto

specification TUserSpecification {
	username
}

之后生成代码

mvn clean install

or

image-20230112172044312

配置

yaml配置

spring:
  application:
    name: jimmer-demo
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost/sbfzl?serverTimezone=GMT%2B8
    username: root
    password: root

jimmer:
    show-sql: true

server:
  port: 8080

dal

package com.example.jimmerstarterjava.dal;

import com.example.jimmerstarterjava.entities.TUser;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.sql.fetcher.Fetcher;
import org.springframework.data.domain.Page;
import org.springframework.lang.Nullable;

import java.util.List;

public interface TUserRepository extends JRepository<TUser, Long> {
    // 不设置限定符的话jimmer会根据方法名自动实现方法体
    // 设置限定符为default后jimmer不再根据方法名自动生成实现
    List<TUser> findByUsernameLikeIgnoreCase(@Nullable String username, Fetcher<TUser> fetcher);
}

controller

package com.example.jimmerstarterjava.controller;

import com.example.jimmerstarterjava.dal.TUserRepository;
import com.example.jimmerstarterjava.entities.TUser;
import com.example.jimmerstarterjava.entities.input.TUserInput;
import com.example.jimmerstarterjava.entities.TUserFetcher;
import lombok.RequiredArgsConstructor;
import org.babyfish.jimmer.client.FetchBy;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.fetcher.Fetcher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Page;

import java.util.List;
import java.util.Objects;

@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class TUserController {
    private final TUserRepository tUserRepository;
    private final JSqlClient sqlClient;


    @GetMapping()
    public Page<TUser> getAll(
        TUserSpecification spec,
        @RequestParam("current", defaultValue = "1") Integer current,
        @RequestParam("pageSize", defaultValue = "10") Integer pageSize
    ) {
        TUserTable table = TUserTable.$;
        return sqlClient
            .createQuery(table)
            .where(spec)
            .select(table)
            .fetchPage(current-1, pageSize);
    }


    @GetMapping("{id}")
    public TUser getById(@PathVariable("id") Long id) {
        return tUserRepository.findById(id).get();
    }

    @PostMapping
    @Transactional
    public TUser insert(@RequestBody TUserInput user) {
        return tUserRepository.sql().getEntities().save(user).getModifiedEntity();
    }

    @PutMapping
    @Transactional
    public TUser update(@RequestBody TUserInput user) {
        return tUserRepository.sql().getEntities().save(user).getModifiedEntity();
    }

    @DeleteMapping("{id}")
    @Transactional
    public void remove(@PathVariable("id") Long id) {
        return tUserRepository.deleteById(id);
    }
}

lombok

java项目常会用到lombok,已经集成lombok的项目不能直接集成jimmer,需要修改一些配置:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <executions>
        <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
        <execution>
            <id>testCompile</id>
            <phase>test-compile</phase>
            <goals>
                <goal>testCompile</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <annotationProcessorPaths>
            <path>
                <groupId>org.babyfish.jimmer</groupId>
                <artifactId>jimmer-apt</artifactId>
                <version>${jimmer.version}</version>
            </path>
            <path>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.24</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

kotlin

添加依赖

plugins {
    // 第一步: 添加ksp插件
	// ksp的版本要和kotlin版本对应,具体参考:https://github.com/google/ksp/releases
    id("com.google.devtools.ksp") version "1.8.0-1.0.9"
}

repositories {
    maven {
        url = uri("https://mirrors.cloud.tencent.com/nexus/repository/maven-public/")
        // 或者这个 url = uri("https://repo.maven.apache.org/maven2/")
    }
    mavenCentral()
}
val jimmerVersion = "0.8.114"

depdencies {
    implementation("org.babyfish.jimmer:jimmer-spring-boot-starter:${jimmerVersion}")
    ksp("org.babyfish.jimmer:jimmer-ksp:${jimmerVersion}")

    // mysql connector
    //runtimeOnly("com.mysql:mysql-connector-j")
	// postgres connector
	runtimeOnly("org.postgresql:postgresql")

}

// 第四步: 讲生成的代码添加到编译目录中。
// 没有这个配置,gradle命令仍然可以正常执行,
// 但是, Intellij无法找到生成的源码。
kotlin {
    sourceSets.main {
        kotlin.srcDir("build/generated/ksp/main/kotlin")
    }
}

配置

yaml配置

spring:
  application:
    name: jimmer-demo
  datasource:
    #driver-class-name: com.mysql.cj.jdbc.Driver
    #url: jdbc:mysql://localhost/<database_name>?serverTimezone=GMT%2B8
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/<database_name>
    username: postgres
    password: postgres

jimmer:
  language: kotlin	
  show-sql: true

server:
  port: 8080

定义Model

import org.babyfish.jimmer.sql.*

@Entity
@Table(name = "t_user")
interface TUser {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    val id: Long
    val username: String
    val password: String
}

定义spec
src/main/dto/com/example/demo/model路径下创建TUser.dto

export com.example.demo.model.TUser
    -> package com.example.demo.model.dto

specification TUserSpecification {
	username
}

生成代码

参照Java部分

执行gradle classes

基础CRUD

  • repository

    import com.example.demo.model.TUser
    import org.babyfish.jimmer.spring.repository.KRepository
    
    interface UserRepository : KRepository<TUser, Long>
    
  • controller

    import com.example.demo.model.TUser
    import com.example.demo.model.dto.TUserSpecification
    import com.example.demo.repository.UserRepository
    import org.babyfish.jimmer.sql.kt.KSqlClient
    import org.springframework.web.bind.annotation.*
    
    @RestController
    @RequestMapping("/u")
    class UserController(
        private val userRepo: UserRepository,
        private val sqlClient: KSqlClient
    ) {
        @GetMapping
        fun get(
            spec: TUserSpecification,
            @RequestParam("current", defaultValue = "1") current: Int,
            @RequestParam("pageSize", defaultValue = "10") pageSize: Int
        ) {
            sqlClient.createQuery(TUser::class) {
                where(spec)
                select(table)
            }.fetchPage(current-1, pageSize)
        }
    
        @GetMapping("{id}")
        fun getOne(@PathVariable("id") id: Long) = userRepo.findById(id)
    
        @PostMapping
        fun addOne(@RequestBody model: TUser) = userRepo.insert(model)
    
        @PutMapping
        fun updateOne(@RequestBody model: TUser) = userRepo.save(model)
    
        @DeleteMapping("{id}")
        fun deleteOne(@PathVariable("id") id: Long) = userRepo.deleteById(id)
    }
    
    

多表查询

定义主表modelBook

@Entity
@Table(name = "book")
interface Book {
    @Id
    @GeneratedValue(generatorType = IdentityIdGenerator::class)
    val id: Long
    val name: String?
    val edition: Long?
    @ManyToOne
    @JoinColumn(name = "book_store_id")
    val store: BookStore?

    @ManyToMany
    @JoinTable(
        name = "book_author_mapping",
        joinColumnName = "book_id",
        inverseJoinColumnName = "author_id"
    )
    val authors: List<Author>
}

其中@ManyToOne注解代表多对一查询,多对一查询还需要@JoinColumn指定属性对应表中字段

@ManyToMany是多对多关系的注解,使用@JoinTable可以映射表和中间表的关系

name值为中间表的表名

joinColumnName是主表的主键在中间表中对应的字段

inverseJoinColumnName是被动表的主键在中间表中对应的字段

定义modelAuthor

@Entity
@Table(name = "author")
interface Author {
    @Id
    @GeneratedValue(generatorType = IdentityIdGenerator::class)
    val id: Long
    @Column(name = "first_name")
    val firstName: String?
    @Column(name = "last_name")
    val lastName: String?
    val gender: Gender?
    @ManyToMany(mappedBy = "authors")
    val books: List<Book>
}

如果model的属性和表中字段不同,可以用@Column指定属性对应表中的字段

被动表中使用@ManytoMany注解的mappedBy指定主表中对应属性的属性名并建立映射

定义modelBookStore

@Entity
@Table(name = "book_store")
interface BookStore {
    @Id
    @GeneratedValue(generatorType = IdentityIdGenerator::class)
    val id: Long
    val name: String?
    @OneToMany(mappedBy = "store")
    val books: List<Book>
}

使用@OneToMany指定一对多关系,mappedBy值指定对应主表中的属性名

一些报错

  • 代码生成成功了但是idea显示类找不到
    image
    解决方法:将annotations目录设置为Generated Sources Root(设置方法为右键点击目录然后点Mark Directory as)

本文作者:七つ一旋桜

本文链接:https://www.cnblogs.com/poifa/p/16667568.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   七つ一旋桜  阅读(511)  评论(1编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起