No 2. JPA(Hibernate) + MySql 5.x integration
Note that the MySQL service must be installed in advance to continue, this section.
1. Create directory structure
2. Add JPA, MySql dependency (pom.xml)
<!--mysql dependency--> <!--mysql dependency and JPA dependency sequence will lead to package import failure--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
3. Update the configuration file (application.properties)
server.port=9527 # ================================ MySQL ================= ==================================================== =========== spring.datasource.url = jdbc:mysql://127.0.0.1:3306/jwtdb?serverTimezone=GMT+8 &useUnicode=true &characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=password spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver # ===================================== JPA ============== ==================================================== ================= #Specify the DBMS spring.jpa.database=MYSQL # Show or not log for each sql query sql spring.jpa.show-sql=true # Hibernate ddl auto (create, create-drop, update) create ?create? spring.jpa.hibernate.ddl-auto=update # Naming strategy spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.DefaultNamingStrategy # stripped before adding them to the entity manager #spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
4. Improve the project structure
4.1 Entity class base class
package com.lc.data.domain; import lombok.Data; import lombok. Getter; import lombok. Setter; import org.hibernate.annotations.GenericGenerator; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.io.Serializable; import java.util.Date; /** * Abstract entity class */ @MappedSuperclass @Data @EntityListeners(AuditingEntityListener. class) @Setter @Getter public abstract class BaseEntity implements Serializable { //https://www.jianshu.com/p/3b384e873232 @Id // @GenericGenerator(name = "uuid-key", strategy = "uuid2") // Custom primary key is not done normally // @GenericGenerator(name = "uuidKey" ,strategy = "com.lc.data.utils.MyUuidKeyGenerator") //custom UUid @GenericGenerator(name = "uuidKey" ,strategy = "org.hibernate.id.UUIDGenerator") // The primary key strategy implemented by the frame @GeneratedValue(generator = "uuidKey") @Column(length = 36) private String id; @CreatedDate @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; @LastModifiedDate @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; }
4.1.1 Create entity class User
package com.example.createpj.data.entity.security; import com.lc.data.domain.BaseEntity; import lombok.Data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import java.io.Serializable; //@Data //moke test? @Entity(name = "user") public class User extends BaseEntity { @Column(length = 32) public String name; @Column(length = 18) public String username; public Integer status; }
4.2 Create corresponding dao, service, controller layers
package com.example.createpj.data.service; import com.example.createpj.data.entity.security.User; import com.example.createpj.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired UserRepository userRepository; public User saveUser(User user, Boolean isFlush) { return userRepository. save(user); } public List<User> findAll() { return userRepository. findAll(); } public List<User> getByName(String name) { return userRepository. getByName(name); } public List<User> getByUsername(String username) { return userRepository. getByUsername(username); } }
package com.example.createpj.repository; import com.example.createpj.data.entity.security.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserRepository extends JpaRepository<User, String> { List<User> getByName(String name); List<User> getByUsername(String username); List<User> findAll(); }
package com.example.createpj.data.utils; import lombok. Getter; import lombok. Setter; @Setter @Getter public class Result { private int code = 200; private String msg = "Operation succeeded"; private Object data; public Result(int code, String msg){ this.code = code; this.msg = msg; } public Result(Object data){ this.data = data; } }
package com.example.createpj.data.utils; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.id.IdentifierGenerator; import java.io.Serializable; import java.util.UUID; /** * Custom primary key generation strategy * com.lc.data.utils.MyIdGenerator IdentityGenerator */ public class MyUuidKeyGenerator implements IdentifierGenerator { @Override public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException { return (Serializable)UUID.randomUUID().toString(); } }
package com.example.createpj; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @SpringBootApplication @EnableJpaAuditing //Enabling annotations that automatically insert time into effect @CreatedDate @LastModifiedDate public class CreatePjApplication { public static void main(String[] args) { SpringApplication.run(CreatePjApplication.class, args); } }
5. Start and access the interface to insert the first data
5.1 Check whether the table is created successfully
5.2 The access interface inserts the first data
Click to add: localhost:9527/user/saveUser?username=12323491 & amp;name=tested h1216
Confirm whether the addition is successful
End of this section.