@MappedSuperclass public class Employee { @Id protected Integer empId; @Version protected Integer version; @ManyToOne @JoinColumn(name="ADDR") protected Address address; public Integer getEmpId() { ... } public void setEmpId(Integer id) { ... } public Address getAddress() { ... } public void setAddress(Address addr) { ... } } // Default table is FTEMPLOYEE table @Entity public class FTEmployee extends Employee { // Inherited empId field mapped to FTEMPLOYEE.EMPID // Inherited version field mapped to FTEMPLOYEE.VERSION // Inherited address field mapped to FTEMPLOYEE.ADDR fk // Defaults to FTEMPLOYEE.SALARY protected Integer salary; public FTEmployee() {} public Integer getSalary() { ... } public void setSalary(Integer salary) { ... } } @Entity @Table(name="PT_EMP") @AssociationOverride(name="address", joincolumns=@JoinColumn(name="ADDR_ID")) public class PartTimeEmployee extends Employee { // Inherited empId field mapped to PT_EMP.EMPID // Inherited version field mapped to PT_EMP.VERSION // address field mapping overridden to PT_EMP.ADDR_ID fk @Column(name="WAGE") protected Float hourlyWage; public PartTimeEmployee() {} public Float getHourlyWage() { ... } public void setHourlyWage(Float wage) { ... } }
@MappedSuperclass public class Employee { @Id protected Integer id; @Version protected Integer version; @ManyToOne protected Address address; public Integer getId() { ... } public void setId(Integer id) { ... } public Address getAddress() { ... } public void setAddress(Address address) { ... } } @Entity @AssociationOverride(name="address", joinColumns=@JoinColumn(name="ADDR_ID")) public class PartTimeEmployee extends Employee { // address field mapping overridden to ADDR_ID foreign key @Column(name="WAGE") protected Float hourlyWage; public Float getHourlyWage() { ... } public void setHourlyWage(Float wage) { ... } }
@Entity public class Employee { @Id int id; @AssociationOverride( name="phoneNumbers", joinTable=@JoinTable( name="EMPPHONES", joinColumns=@JoinColumn(name="EMP"), inverseJoinColumns=@JoinColumn(name="PHONE") ) ) @Embedded ContactInfo contactInfo; ... } @Embeddable public class ContactInfo { @ManyToOne Address address; // Unidirectional @ManyToMany(targetEntity=PhoneNumber.class) List phoneNumbers; } @Entity public class PhoneNumber { @Id int number; @ManyToMany(mappedBy="contactInfo.phoneNumbers") Collection<Employee> employees; }
@Target({TYPE}) @Retention(RUNTIME) public @interface Cacheable { boolean value() default true; }
Example 1: Convert a basic attribute @Converter public class BooleanToIntegerConverter implements AttributeConverter<Boolean, Integer> { ... } @Entity public class Employee { @Id long id; @Convert(BooleanToIntegerConverter.class) boolean fullTime; ... } Example 2: Auto-apply conversion of a basic attribute @Converter(autoApply=true) public class EmployeeDateConverter implements AttributeConverter<com.acme.EmployeeDate, java.sql.Date> { ... } @Entity public class Employee { @Id long id; ... // EmployeeDateConverter is applied automatically EmployeeDate startDate; } Example 3: Disable conversion in the presence of an autoapply converter @Convert(disableConversion=true) EmployeeDate lastReview; Example 4: Apply a converter to an element collection of basic type @ElementCollection // applies to each element in the collection @Convert(NameConverter.class) List<String> names; Example 5: Apply a converter to an element collection that is a map or basic values. The converter is applied to the map value. @ElementCollection @Convert(EmployeeNameConverter.class) Map<String, String> responsibilities; Example 6: Apply a converter to a map key of basic type @OneToMany @Convert(converter=ResponsibilityCodeConverter.class, attributeName="key") Map<String, Employee> responsibilities; Example 7: Apply a converter to an embeddable attribute @Embedded @Convert(converter=CountryConverter.class, attributeName="country") Address address; Example 8: Apply a converter to a nested embeddable attribute @Embedded @Convert(converter=CityConverter.class, attributeName="region.city") Address address; Example 9: Apply a converter to a nested attribute of an embeddable that is a map key of an element collection @Entity public class PropertyRecord { ... @Convert(name="key.region.city", converter=CityConverter.class) @ElementCollection Map<Address, PropertyInfo> parcels; } Example 10: Apply a converter to an embeddable that is a map key for a relationship @OneToMany @Convert(attributeName="key.jobType", converter=ResponsibilityTypeConverter.class) Map<Responsibility, Employee> responsibilities; Example 11: Override conversion mappings for attributes inherited from a mapped superclass @Entity @Converts({ @Convert(attributeName="startDate", converter=DateConverter.class), @Convert(attributeName="endDate", converter=DateConverter.class)}) public class FullTimeEmployee extends GenericEmployee { ... }
@Entity @EntityListeners(com.acme.AlertMonitor.class) public class Account { Long accountId; Integer balance; boolean preferred; @Id public Long getAccountId() { ... } ... public Integer getBalance() { ... } ... @Transient // because status depends upon non-persistent context public boolean isPreferred() { ... } ... public void deposit(Integer amount) { ... } public Integer withdraw(Integer amount) throws NSFException {... } @PrePersist protected void validateCreate() { if (getBalance() < MIN_REQUIRED_BALANCE) throw new AccountException("Insufficient balance to open an account"); } @PostLoad protected void adjustPreferredStatus() { preferred = (getBalance() >= AccountManager.getPreferredStatusLevel()); } } public class AlertMonitor { @PostPersist public void newAccountAlert(Account acct) { Alerts.sendMarketingInfo(acct.getAccountId(), acct.getBalance()); } }
@Entity @EntityListeners(com.acme.AlertMonitor.class) public class Account { Long accountId; Integer balance; boolean preferred; @Id public Long getAccountId() { ... } ... public Integer getBalance() { ... } ... @Transient // because status depends upon non-persistent context public boolean isPreferred() { ... } ... public void deposit(Integer amount) { ... } public Integer withdraw(Integer amount) throws NSFException {... } @PrePersist protected void validateCreate() { if (getBalance() < MIN_REQUIRED_BALANCE) throw new AccountException("Insufficient balance to open an account"); } @PostLoad protected void adjustPreferredStatus() { preferred = (getBalance() >= AccountManager.getPreferredStatusLevel()); } } public class AlertMonitor { @PostPersist public void newAccountAlert(Account acct) { Alerts.sendMarketingInfo(acct.getAccountId(), acct.getBalance()); } }
Example 1: @Entity public class Course { ... @ManyToMany @OrderBy("lastname ASC") public List<Student> getStudents() {...}; ... } Example 2: @Entity public class Student { ... @ManyToMany(mappedBy="students") @OrderBy // PK is assumed public List<Course> getCourses() {...}; ... } Example 3: @Entity public class Person { ... @ElementCollection @OrderBy("zipcode.zip, zipcode.plusFour") public Set<Address> getResidences() {...}; ... }
@Entity public class Employee { @Id int id; @Transient User currentUser; ... }
// Entity EntityGraph @Entity @Table(name = "order") @Named(name = "graphOrderItems", attributeNodes = @NamedAttributeNode(attributeNodes = "items") ) public class Order implements Serializable { ... @OneToMany(mappedBy = "order", fetch = FetchType.LAZY) private Set<Item> items = new HashSet<Item>(); @OneToMany(mappedBy = "order", fetch = FetchType.EAGER) private Set<Features> features = new HashSet<Features>(); @OneToMany(mappedBy = "order", fetch = FetchType.LAZY) private Set<Comment> comments = new HashSet<Comment>(); ... // c javax.persistence.fetchgraph .. EntityGraph graph = this.em.getEntityGraph("graphOrderItems"); Map hints = new HashMap(); hints.put("javax.persistence.fetchgraph", graph); return this.em.find(Order.class, orderId, hints); // items fetchType = EAGER, features comments fetchType = LAZY // c javax.persistence.loadgraph .. EntityGraph graph = this.em.getEntityGraph("graphOrderItems"); Map hints = new HashMap(); hints.put("javax.persistence.loadgraph", graph); return this.em.find(Order.class, orderId, hints); // items features fetchType = EAGER, comments fetchType = LAZY
CriteriaBuilder cb = ... CriteriaQuery<Customer> q = cb.createQuery(Customer.class); Root<Customer> customer = q.from(Customer.class); q.select(customer);
Source: https://habr.com/ru/post/265061/
All Articles