Benx Blog

八月 8, 2014

Diigo Diary 08/08/2014

Filed under: Diigo Diary — benxshen @ 8:30 上午
  • tags: JPA spring testing

    • import org.springframework.data.jpa.repository.JpaRepository;
      import org.springframework.data.jpa.repository.Query;
      import org.springframework.data.repository.query.Param;
       
      import java.util.List;
       
      public interface TodoRepository extends JpaRepository<Todo, Long> {
       
          @Query(
                  "Select t FROM Todo t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', :searchTerm, '%')) " +
                  "OR LOWER(t.description) LIKE LOWER(CONCAT('%', :searchTerm, '%'))"
          )
          public List<Todo> search(@Param("searchTerm") String searchTerm);
      }
  • tags: JPA mapping

    • @Entity @Table(name = “stock", catalog = “mkyongdb", uniqueConstraints = {  @UniqueConstraint(columnNames = “STOCK_NAME"),  @UniqueConstraint(columnNames = “STOCK_CODE") }) public class Stock implements java.io.Serializable {
    • @OneToMany(fetch = FetchType.LAZY, mappedBy = “pk.stock", cascade=CascadeType.ALL)  public Set<StockCategory> getStockCategories() {  return this.stockCategories;  }
    • @Entity @Table(name = “stock_category", catalog = “mkyongdb") @AssociationOverrides({  @AssociationOverride(name = “pk.stock",   joinColumns = @JoinColumn(name = “STOCK_ID")),  @AssociationOverride(name = “pk.category",   joinColumns = @JoinColumn(name = “CATEGORY_ID")) }) public class StockCategory implements java.io.Serializable {
    • @EmbeddedId  public StockCategoryId getPk() {  return pk;  }
    • @Transient  public Stock getStock() {  return getPk().getStock();  }  
    • @Transient  public Category getCategory() {  return getPk().getCategory();  }
    • @Temporal(TemporalType.DATE)  @Column(name = “CREATED_DATE", nullable = false, length = 10)  public Date getCreatedDate() {  return this.createdDate;  }
    • @OneToMany(fetch = FetchType.LAZY, mappedBy = “pk.category")  public Set<StockCategory> getStockCategories() {  return this.stockCategories;  }
  • tags: JPA mapping

    • @Entity @Table(name = “stock", catalog = “mkyongdb", uniqueConstraints = {  @UniqueConstraint(columnNames = “STOCK_NAME"),  @UniqueConstraint(columnNames = “STOCK_CODE") }) public class Stock implements java.io.Serializable {
    • Table(name = “stock", catalog = “mkyongdb", uniqueConstraints = {  @UniqueConstraint(columnNames = “STOCK_NAME"),  @UniqueConstraint(columnNames = “STOCK_CODE") })
    • @GenericGenerator(name = “generator", strategy = “foreign",   parameters = @Parameter(name = “property", value = “stock"))  @Id  @GeneratedValue(generator = “generator")  @Column(name = “STOCK_ID", unique = true, nullable = false)  public Integer getStockId() {  return this.stockId;  }
    • @OneToOne(fetch = FetchType.LAZY)  @PrimaryKeyJoinColumn  public Stock getStock() {  return this.stock;  }
    • @Temporal(TemporalType.DATE)  @Column(name = “LISTED_DATE", nullable = false, length = 10)  public Date getListedDate() {  return this.listedDate;  }
  • tags: JPA

    • A ManyToMany relationship in Java is where the source object has an attribute that stores a collection of target objects and (if) those target objects had the inverse relationship back to the source object it would also be a ManyToMany relationship.
    • The main difference between a OneToMany and a ManyToMany relationship in JPA is that a ManyToMany always makes use of a intermediate relational join table to store the relationship, where as a OneToMany can either use a join table, or a foreign key in target object’s table referencing the source object table’s primary key.
    • All ManyToMany relationships require a JoinTable. The JoinTable is defined using the @JoinTable annotation
    • @Entity public class Employee {  @Id  @Column(name=“ID")  private long id;  …  @ManyToMany  @JoinTable(  name=“EMP_PROJ",  joinColumns={@JoinColumn(name=“EMP_ID", referencedColumnName=“ID")},  inverseJoinColumns={@JoinColumn(name=“PROJ_ID", referencedColumnName=“ID")})  private List<Project> projects;
    • Although a ManyToMany relationship is always bi-directional on the database, the object model can choose if it will be mapped in both directions, and in which direction it will be mapped in. If you choose to map the relationship in both directions, then one direction must be defined as the owner and the other must use the mappedBy attribute to define its mapping. This also avoids having to duplicate the JoinTable information in both places.
    • As with all bi-directional relationships it is your object model’s and application’s responsibility to maintain the relationship in both direction. There is no magic in JPA, if you add or remove to one side of the collection, you must also add or remove from the other side, see object corruption.
    • Technically the database will be updated correctly if you only add/remove from the owning side of the relationship, but then your object model will be out of synch, which can cause issues.
    • @Entity public class Project {  @Id  @Column(name=“ID")  private long id;  …  @ManyToMany(mappedBy=“projects")  private List<Employee> employees;  … }
    • Object not in collection after refresh.[edit]

       

       
      If you have a bi-directional ManyToMany relationship, ensure that you add to both sides of the relationship.

       

      See Object corruption.
    • Duplicate rows inserted into the join table.[edit]

       

       
      If you have a bidirectional ManyToMany relationship, you must use mappedBy on one side of the relationship, otherwise it will be assumed to be two difference relationships and you will get duplicate rows inserted into the join table.
  • tags: JPA

  • tags: JPA

  • tags: JPA

  • tags: JPA java

  • tags: jpa java tutorial document

    • JavaConfig, like the core Spring Framework, supports use of JSR-250  “Common Annotations". For example: 

      public class FooService {     @PostConstruct     public void init() {         // custom initialization logic     } }  @Configuration @AnnotationDrivenConfig public class ApplicationConfig {     @Bean     public FooService fooService() {         return new FooService();     } }                     

       

    • 2.2.3.3.   Using @Bean initMethodName / destroyMethodName  attributes 

        The @Bean annotation supports specifying arbitrary initialization and  destruction callback methods, much like Spring XML’s  init-method and destroy-method attributes to  the bean element:

      • 1.2. What JavaConfig requires to run

        • Java 5.0 or higher

        • Spring 2.5.6 or higher

        • AspectJ 1.6.2 or higher

        • CGLIB 2.1.3

      • By relying only on basic Java syntax and language features, JavaConfig offers  several distinct advantages: 

        •   JavaConfig provides a truly object-oriented mechanism for dependency injection,  meaning you can take full advantage of reuse, inheritance and polymorphism in  your configuration code. 
        •   You are given complete control over instantiation and dependency injection,  meaning that even the most complex objects can be dealt with gracefully. 
        •   Because only Java is required, you are left with fully refactorable  configuration logic that requires no special tooling beyond your IDE.

Posted from Diigo. The rest of my favorite links are here.

發表迴響 »

仍無迴響。

RSS feed for comments on this post. TrackBack URI

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

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

Twitter picture

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

Facebook照片

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

Google+ photo

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

連結到 %s

在 WordPress.com 建立免費網站或網誌.

%d 位部落客按了讚: