关于@Entity和@Table注解的用法详解
作者:光阴不负卿 时间:2022-05-15 15:29:04
@Entity和@Table注解的用法
@Entity注解
@Entity注解和@Table注解都是Java Persistence API中定义的一种注解。
@Entity说明这个class是实体类,并且使用默认的orm规则,即class名就是数据库表中表明,class字段名即表中字段名。@Entity注解指明这是一个实体Bean。
import lombok.Data;
import javax.persistence.*;
@Data
@Entity(name = "t_book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "book_name")
private String name;
@Column(name = "book_author")
private String author;
private Float price;
@Transient
private String description;
}
@Entity注解表示该类是要给实体类,在羡慕启动时会根据该类自动生成一张表,表的名称即@Entity注解中name的值,如果不配置name,默认表明为类名
所有的实体类都要有主键,@Id注解表示该属性是一个主键,@GeneratedValue注解表示注解自动生成,strategy则表示主键的生成策略
默认情况下,生成的表中字段的名称就是实体类中属性的名称,通过@Column注解可以定制生成的字段属性,name表示该属性对应的数据表中字段的名称,nullable表示该字段非空
@Transient注解表示在生成数据库中的表时,该属性被忽略,即不生成对应的字段
@Table注解
@Table注解默认情况下只会完成表和实体之间的映射,声明才对象映射到数据库的数据表,通过它可以为实体指定表(table)
@Data
@Table(name="book")
public class Book{
@Id
private Integer id;
@Column(name="book_name")
private String name;
...
}
常用属性:name 指定表
@Table(name = "book")
@Table注解是一个非必须的注解,@Table注解指定了Entity所要映射的数据库表,其中@Table.name()用来指定映射表的表名。
如果同时使用了@Entity(name="student")和@Table(name="book"),最终对应的表名是book,这说明优先级:@Table>@Entity
@Entity和@Table的区别
Java Persistence API定义了一种定义,可以将常规的普通Java对象(有时被称作POJO)映射到数据库。这些普通Java对象被称作Entity Bean。除了是用Java Persistence元数据将其映射到数据库外,Entity Bean与其他Java类没有任何区别。
事实上,创建一个Entity Bean对象相当于新建一条记录,删除一个Entity Bean会同时从数据库中删除对应记录,修改一个Entity Bean时,容器会自动将Entity Bean的状态和数据库同步。
@Entity和@Table的区别:
@Entity说明这个class是实体类,并且使用默认的orm规则,即class名即数据库表中表名,class字段名即表中的字段名
如果想改变这种默认的orm规则,就要使用@Table来改变class名与数据库中表名的映射规则,@Column来改变class中字段名与db中表的字段名的映射规则
来源:https://blog.csdn.net/li_w_ch/article/details/110939776
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java类加载机制、类加载器、自定义类加载器的案例
![](https://img.aspxhome.com/file/2023/7/79307_0s.jpg)
Java中mybatis的三种分页方式
![](https://img.aspxhome.com/file/2023/7/67607_0s.png)
Java中break、continue、return在for循环中的使用
SpringBoot后端上传文件类型检测方式
![](https://img.aspxhome.com/file/2023/6/63296_0s.jpg)
springboot2中session超时,退到登录页面方式
Java日常练习题,每天进步一点点(3)
Android RecyclerView详解及简单实例
关于Springboot中JSCH的使用及说明
C#策略模式(Strategy Pattern)实例教程
![](https://img.aspxhome.com/file/2023/5/71075_0s.png)
java使用HashMap实现斗地主(有序版)
Android开发 旋转屏幕导致Activity重建解决方法
C#抓取网络图片保存到本地的实现方法
.NET垃圾回收器(GC)原理浅析
![](https://img.aspxhome.com/file/2023/6/102396_0s.png)
手把手教你SpringBoot快速集成Swagger的配置过程
![](https://img.aspxhome.com/file/2023/5/58705_0s.png)
Java并发编程之显示锁ReentrantLock和ReadWriteLock读写锁
javaweb实战之商城项目开发(三)
![](https://img.aspxhome.com/file/2023/4/97804_0s.png)
springboot整合spring-retry的实现示例
![](https://img.aspxhome.com/file/2023/0/80170_0s.png)
手把手带你实现一个萌芽版的Spring容器
![](https://img.aspxhome.com/file/2023/9/94759_0s.png)
使用Jenkins来构建SVN+Maven项目的实现
![](https://img.aspxhome.com/file/2023/0/61840_0s.jpg)
Java多个版本切换的几种方法
![](https://img.aspxhome.com/file/2023/8/63108_0s.png)