当前位置:编程学习 > JSP >>

Hibernate Annotations(四)

普通一对多(延迟加载方式) 



 @OneToMany(mappedBy = "troop", cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
    @OrderBy(clause 
= "name desc"
)
    
public Set<Soldier> getSoldiers() 
{
        
return
 soldiers;
    }


    @ManyToOne(fetch 
= FetchType.EAGER)
    @JoinColumn(name 
= "troop_fk"
)
    
public Troop getTroop() 
{
        
return
 troop;
    }

DeleteOrphan模式



 @OneToMany(mappedBy = "troop", cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
    @OrderBy(clause 
= "name desc"
)
    @org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    
public Set<Soldier> getSoldiers() 
{
        
return
 soldiers;
    }


    troop.getSoldiers().clear();
    s 
= openSession();
    tx 
=
 s.beginTransaction();
    s.merge( troop );
    tx.commit();
    s.close();

 OneToManySet



    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name 
= "CUST_ID"
)
    @Sort(type 
= SortType.COMPARATOR, comparator = TicketComparator.class
)
    
public SortedSet<Ticket> getTickets() 
{
        
return
 tickets;
    }


   
public class TicketComparator implements Comparator<Ticket> {

    
public int compare(Ticket ticket, Ticket ticket1) 
{
        
if ( ticket == null || ticket1 == null ) 
{
            
throw new IllegalStateException( "Ticket comparison only available through non null        tickets"
 );
        }

    
return ticket1.getNumber().length() - ticket.getNumber().length();

    }

}

OneToManyCollection



    @OneToMany(targetEntity = org.hibernate.test.annotations.Discount.class,
            cascade 
= CascadeType.ALL, mappedBy = "owner"
)
    @Cascade(
{ALL}
)
    
public Collection getDiscountTickets() 
{
        
return
 discountTickets;
    }

JoinColumns



    @OneToMany(cascade = CascadeType.ALL, mappedBy = "parent")
    @BatchSize(size 
= 5
)
    @javax.persistence.OrderBy(
"favoriteSuperhero asc, favoriteSinger desc"
)
    
public Set<Child>
 children;

    @ManyToOne()
    @JoinColumns(
{
    @JoinColumn(name 
= "parentCivility", referencedColumnName = "isMale"
),
    @JoinColumn(name 
= "parentLastName", referencedColumnName = "lastName"
),
    @JoinColumn(name 
= "parentFirstName", referencedColumnName = "firstName"
)
            }
)
    
public
 Parent parent;
    @Column(name 
= "fav_sup_hero"
)
    
public
 String favoriteSuperhero;
    @Column(name 
= "fav_singer"
)
    
public String favoriteSinger;

注:cascade的值只能从CascadeType.PERSIST(级联新建)、CascadeType.REMOVE(级联删除)、CascadeType.REFRESH(级联刷新)、CascadeType.MERGE(级联更新)中选择一个或多个。还有一个选择是使用CascadeType.ALL,表示选择全部四项。



<
补充:Jsp教程,Java基础
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,