先贴下自己的简单代码
import javax.persistence.*; import java.util.Date; import java.util.UUID; @Entity @Table(name = "vehicle") public class Vehicle { /** serialVersionUID. */ private static final long serialVersionUID = 1L; /** 主键. */ @Id @GeneratedValue private UUID t_id; private Date created_at = new Date(); private Date modified_at = new Date(); @Column(unique = true) private String id; public UUID getT_id() { return t_id; } public void setT_id(UUID t_id) { this.t_id = t_id; } public Date getCreated_at() { return created_at; } public void setCreated_at(Date created_at) { this.created_at = created_at; } public Date getModified_at() { return modified_at; } public void setModified_at(Date modified_at) { this.modified_at = modified_at; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Vehicle() { } public Vehicle(UUID t_id, Date created_at, Date modified_at, String id) { this.t_id = t_id; this.created_at = created_at; this.modified_at = modified_at; this.id = id; } }
import org.springframework.data.jpa.repository.JpaRepository; public interface VehicleRepos extends JpaRepository<Vehicle, String> { }
public void addData() { Date now = new Date(); Vehicle vehicle = new Vehicle(UUID.randomUUID(), now, now, "vehicleid02"); vehicleRepos.save(vehicle); }
spring: datasource: url: jdbc:postgresql://<ip>:<port>/<db name> username: postgres password: postgres jpa: show-sql: true hibernate: ddl-auto: update properties: hibernate: dialect: org.hibernate.dialect.PostgreSQLDialect temp: use_jdbc_metadata_defaults: false
也记录下sping小白第一次用spring data jpa遇到的问题
1 user表的问题
小知识点:在postgresql中,默认有一张user表用来存放postgresql的用户,所以当我们自己建立一个user表的时候,优先访问系统默认的user表。当我们想访问自己创建的user表的时候,需要加public前缀(public.user).
所以第一次建表时刚好踩到这个坑,执行后进postgres看,user表根据代码中model自动创建了,save方法也执行成功了,但是select的时候又没有数据
2 空的构造函数
报错: org.springframework.orm.jpa.JpaSystemException: No default constructor for entity
需要给数据库表model增加一个空的构造函数