#onenote# JPA

1.

A JPA entity must have some Id defined. But a JPA Id does not necessarily have to be mapped on the table primary key, use @EmbeddedId for composite key

 

@Entity
@Table(name=”entity_property”)
public class EntityProperty {
@EmbeddedId
private EntityPropertyPK id;

@Column(name = “value”)
private String value;


}

 

  1. AttributeOverride

@Entity

public class Office {

 

@TableGenerator(name = “office_gen”, pkColumnName = “gen_name”, valueColumnName = “gen_val”, table = “id_gen”)

@Id

@GeneratedValue(generator = “office_gen”, strategy = GenerationType.TABLE)

private int idoffice;

 

@Embedded

@AttributeOverrides({

@AttributeOverride(name = “area”, column = @Column(name = “landmark”)),

@AttributeOverride(name = “pincode”, column = @Column(name = “postal_code”)) })

private Address address;

 

Address ‘ property  “area”  <– entity_property.landmark

Address ‘ property  “pincode”  <–  entity_property.postal_code

 

 

 

  • JpaRepository的查询

 

直接在接口中定义查询方法,如果是符合规范的,可以不用写实现,目前支持的关键字写法如下:

 

 

 

Pasted from <http://sishuok.com/forum/blogPost/list/7000.html>

 

 

Spring Data JPA框架在进行方法名解析时,会先把方法名多余的前缀截取掉,比如 find、findBy、read、readBy、get、getBy,然后对剩下部分进行解析。

假如创建如下的查询:findByUserDepUuid(),框架在解析该方法时,首先剔除 findBy,然后对剩下的属性进行解析,假设查询实体为Doc

1:先判断 userDepUuid (根据 POJO 规范,首字母变为小写)是否为查询实体的一个属性,如果是,则表示根据该属性进行查询;如果没有该属性,继续第二步;

2:从右往左截取第一个大写字母开头的字符串此处为Uuid),然后检查剩下的字符串是否为查询实体的一个属性,如果是,则表示根据该属性进行查询;如果没有该属性,则重复第二步,继续从右往左截取;最后假设user为查询实体的一个属性;

3:接着处理剩下部分(DepUuid),先判断 user 所对应的类型是否有depUuid属性,如果有,则表示该方法最终是根据 “ Doc.user.depUuid” 的取值进行查询;否则继续按照步骤 2 的规则从右往左截取,最终表示根据 “Doc.user.dep.uuid” 的值进行查询。

4:可能会存在一种特殊情况,比如 Doc包含一个 user 的属性,也有一个 userDep 属性,此时会存在混淆。可以明确在属性之间加上 “_” 以显式表达意图,比如 “findByUser_DepUuid()” 或者 “findByUserDep_uuid()”

特殊的参数: 还可以直接在方法的参数上加入分页或排序的参数,比如:

Page<UserModel> findByName(String name, Pageable pageable);

List<UserModel> findByName(String name, Sort sort);

 

 

 

 

  • Return Boolean Value from Spring Data JPA Query

 

@Repository
public interface CompanyRepository extends JpaRepository<Company, Integer> {
@Query(“SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Company c WHERE c.name = :companyName”)
boolean existsByName(@Param(“companyName”) String companyName);
}

 

  1. @id   <–  no must to be long, can be string, date, int..

 

Annotation Id

Target:

Fields (including property get methods)

Specifies the primary key of an entity. The field or property to which the Id annotation is applied should be one of the following types: any Java primitive type; any primitive wrapper type; String;java.util.Date; java.sql.Date; java.math.BigDecimal; java.math.BigInteger.

The mapped column for the primary key of the entity is assumed to be the primary key of the primary table. If no Column annotation is specified, the primary key column name is assumed to be the name of the primary key property or field.

  1. One to One releationship

 

@Entity

@Table(name=“COMPANY”)

public class Company  // <— Host/Parent class

{

private Industry industry;

private String industryCode;

 

@OneToOne(fetch = FetchType.LAZY)

@JoinColumn(name=”INDUSTRY_CODE”)  //INDUSTRY_CODE  is the column name in DB of COMPANY table

public Industry getIndustry() {

return industry;

}

 

// No need, otherwise: Repeated column in mapping for entity

@JoinColumn(name=”INDUSTRY_CODE”)

Public String getIndustryCode()

{

}

}

 

@Entity

@Table(name=“INDUSTRY”)

public class Industry  // <– Ref/Child class

{

private String industryCode;

private Company company;

 

@Id

@Column(name = “INDUSTRY_CODE”)

public String getIndustryCode() {

return industryCode;

}

 

@OneToOne(cascade=CascadeType.ALL, mappedBy=”industryCode”)  // industryCode is the property of Company class

public Company getCompany() {

return company;

}

}

 

 

For mapping a composite key, there are a couple of options. You can

  • Define a separate @Embeddable object with the PK fields and use it as @EmbeddedId in your @Entity class
    @Embeddable
    public class MyCompositePK {
    @Column
    private String fieldA;
    @Column
    private String fieldB;
    }
    @Entity
    public class MyBean {
    @EmbeddedId
    private MyCompositePK id;
    @Column
    private String fieldC;
    }
  • Define a non-mapped POJO with the PK fields and use it as @IdClass in the @Entity.
    @Entity
    @IdClass(value=ClassAB.ClassABId.class)
    public class ClassAB implements Serializable {
    private String idA;
    private String idB;

    @Id
    @Column(name=”ID_A”)
    public String getIdA(){ return idA; }
    public void setIdA(String idA){ this.idA = idA; }

    @Id
    @Column(name=”ID_B”)
    public String getIdB(){ return idB; }
    public void setIdB(String idB){ this.idB = idB; }

    static class ClassABId implements Serializable {
    private String idA;
    private String idB;

    public String getIdA(){ return idA; }
    public void setIdA(String idA){ this.idA = idA; }

    public String getIdB(){ return idB; }
    public void setIdB(String idB){ this.idB = idB; }

    // implement equals(), hashcode()
    }
    }
    In this example ClassABId is a static inner class just for convenience.

 

Pasted from <http://stackoverflow.com/questions/14729206/jpa-table-with-2-primary-key-fields>

 

JPA vs hibernate

As you state JPA is just a specification, meaning there is no implementation. You can annotate your classes as much as you would like with JPA annotations, however without an implementation nothing will happen. Think of JPA as the guidelines that must be followed or an interface, while Hibernate’s JPA implementation is code that meets the API as defined by the JPA specification and provides the under the hood functionality.

JPA is the dance, Hibernate is the dancer.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s