hibernate annotation总结

采用hibernate 3.6 final版实验。

类图:

hibernate annotation总结_第1张图片


代码:

Salesman.java:

package basicCar.bean;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
//import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;


@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
@Table(name = "salesman")
public class Salesman implements java.io.Serializable {
	@Id
	@GeneratedValue(generator = "mysqlIncrement")
	@GenericGenerator(name = "mysqlIncrement", strategy = "increment")
	private long sid;
	//@Length(min=1,max=3)
	
	@Column
	private String salesName;
	
	@OneToOne(mappedBy="salesman",cascade=CascadeType.ALL)
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
	private Alias alias;

	
	
	@OneToMany(mappedBy="salesman",cascade = CascadeType.ALL)//双向一对多
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
	private Set carOrders = new HashSet();
	
	@ManyToMany(           //双向多对多
			targetEntity=basicCar.bean.BasicCar.class,
			cascade = CascadeType.ALL
			)         
	@JoinTable(
			name = "carorder",
			joinColumns = { @JoinColumn(name = "salesId")} ,
			inverseJoinColumns={@JoinColumn(name="carId")}
			)
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
	private Set cars = new HashSet();

    @Embedded           //搞定映射组件
	@AttributeOverrides({
		@AttributeOverride(name="province", column=@Column(name="province")),
		@AttributeOverride(name="city", column=@Column(name="city")),
		@AttributeOverride(name="street", column=@Column(name="street")),
		@AttributeOverride(name="number", column=@Column(name="number"))
	})
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) 
	private Address address;
    /*	
	@Embedded
	@AttributeOverrides({
		@AttributeOverride(name="province", column=@Column(name="wprovince")),
		@AttributeOverride(name="city", column=@Column(name="wcity")),
		@AttributeOverride(name="street", column=@Column(name="wstreet")),
		@AttributeOverride(name="number", column=@Column(name="wnumber"))
	})
	private Address waddress;*/
	
	public Salesman() {
	}
	
	public Salesman(String N) {
		this.salesName = N;
	}

	public long getSid() {
		return this.sid;
	}

	private void setSid(long sid) {
		this.sid = sid;
	}

	public String getSalesname() {
		return this.salesName;
	}

	public void setSalesname(String salesName) {
		this.salesName = salesName;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public Address getAddress() {
		return address;
	}

	public void setCarOrders(Set carOrders) {
		this.carOrders = carOrders;
	}

	public Set getCarOrders() {
		return carOrders;
	}

	public void setAlias(Alias alias) {
		this.alias = alias;
	}

	public Alias getAlias() {
		return alias;
	}

	public void setCars(Set cars) {
		this.cars = cars;
	}

	public Set getCars() {
		return cars;
	}



	
	
	/*public Set getAliases() {
		return this.aliases;
		}

		public void setAliases(Set s){
		this.aliases=s;
		}*/

    /*public Address getaddress() {
		return this.address;
	}

	public void sethaddress(Address a) {
		this.address = a;
	}*/
	/*	
	public Address getwaddress() {
		return this.waddress;
	}

	public void setwaddress(Address a) {
		this.waddress = a;
	}*/
}

Alias.java:

package basicCar.bean;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Version;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.CacheConcurrencyStrategy;


@Entity
@Table(name = "alias")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
public class Alias implements java.io.Serializable{
	/*@Id
	@GeneratedValue(generator = "mysqlIncrement")
	@GenericGenerator(name = "mysqlIncrement", strategy = "increment")
	private long aid;*/
	
	@Id
	@GeneratedValue(generator = "mysqlIncrement")
	@GenericGenerator(name = "mysqlIncrement", strategy = "increment")
	private long aid;
	
	@Column
	private String aliasName;
	
	@Column
	private Long amoney;
	
	@Version
	@Column(name="version",nullable=false,unique=true)
	private int version;
	
	@OneToOne(cascade=CascadeType.ALL)
	@PrimaryKeyJoinColumn
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
	private Salesman salesman;
	
	
	
	public Alias(){}
	


	public void setAliasName(String aliasName) {
		this.aliasName = aliasName;
	}

	public String getAliasName() {
		return aliasName;
	}
	public void setSalesman(Salesman salesman) {
		this.salesman = salesman;
	}
	public Salesman getSalesman() {
		return salesman;
	}



	public void setAid(long aid) {
		this.aid = aid;
	}



	public long getAid() {
		return aid;
	}



	public void setVersion(int version) {
		this.version = version;
	}



	public int getVersion() {
		return version;
	}



	public void setAmoney(Long amoney) {
		this.amoney = amoney;
	}



	public Long getAmoney() {
		return amoney;
	}
	
	


}

BasicCar.java:

package basicCar.bean;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
@Table(name="basiccar")
public class BasicCar implements java.io.Serializable {
	@Id
	@GeneratedValue(generator="mysqlIncrement")
	@GenericGenerator(name="mysqlIncrement", strategy="increment")
	private long id; 
	
	@Column(name = "name")
	private String name;
	@Column(name = "factory" , length=50)
	@Lob
	private String factory;
	@Column(name = "date")
	//@Temporal(TemporalType.TIME)出错Data truncated for column 'date' at row 1
	@Temporal(TemporalType.DATE)
	@Basic(fetch=FetchType.LAZY)
	private Date date;

	@ManyToMany(
			mappedBy="cars",
			targetEntity=basicCar.bean.Salesman.class,
			cascade = {CascadeType.PERSIST,CascadeType.MERGE}
				)
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
	private Set salesmans = new HashSet();
	
	public BasicCar() {
	}
	
	public BasicCar(String N) {
		this.name = N;
	}

	public BasicCar(String name, String factory, Date date) {
		this.name = name;
		this.factory = factory;
		this.date = date;
	}

	public long getId() {
		return this.id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getFactory() {
		return this.factory;
	}

	public void setFactory(String factory) {
		this.factory = factory;
	}

	public Date getDate() {
		return this.date;
	}

	public void setDate(Date date) {
		this.date = date;
	}
	
	 public boolean eauals(Object o){
		 
		  if(this==o)
			  return true;
		  
		  if(!(o instanceof BasicCar))
			  return false;
		  
		  final BasicCar other=(BasicCar)o;
		  if(this.getName().equals(other.getName())
				  &&this.getDate().equals(other.getDate()) 
						  &&this.getFactory().equals(other.getFactory()))
						  return true;
		  else 
			  return false;	    
	  }

	public void setSalesmans(Set salesmans) {
		this.salesmans = salesmans;
	}

	public Set getSalesmans() {
		return salesmans;
	}
}

CarOrder.java:

package basicCar.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;


@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) 
@Table(name = "carorder1")
public class CarOrder implements java.io.Serializable {
	@Id
	@GeneratedValue(generator = "mysqlIncrement")
	@GenericGenerator(name = "mysqlIncrement", strategy = "increment")
	private long cid;

	@Column
	private String carName;

	
	
	@ManyToOne
	@JoinColumn(name = "salesId")
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	private Salesman salesman;

	public CarOrder() {
	}

	public CarOrder(String name) {
		this.carName = name;
	}

	public long getCid() {
		return this.cid;
	}

	public void setCid(long id) {
		this.cid = id;
	}

	public String getcarname() {
		return this.carName;
	}

	public void setcarname(String cName) {
		this.carName = cName;
	}

	public Salesman getSalesman() {
		return this.salesman;
	}

	public void setSalesman(Salesman salesman) {
		this.salesman = salesman;
	}

	
}

Address.java:

package basicCar.bean;

import javax.persistence.Column;
import javax.persistence.Embeddable;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@SuppressWarnings("serial")
@Embeddable
public class Address implements java.io.Serializable  {
	@Column
	private String province;
	@Column
	private String city;
	@Column
	private String street;
	@Column
	private String number;
	
	public Address(){}
	
	public Address(String P,String C,String S,String N)
	{
		this.province=P;
		this.city=C;
		this.street=S;
		this.number=N;
	}
	
	public void setProvince(String province) {
		this.province = province;
	}
	public String getProvince() {
		return province;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getCity() {
		return city;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	public String getStreet() {
		return street;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public String getNumber() {
		return number;
	}

}

hibernate.hbm.xml:




    
        com.mysql.jdbc.Driver
        001052
        jdbc:mysql://localhost:3306/chwa
        root
        org.hibernate.dialect.MySQLDialect
        
        
        2
        
        
       org.hibernate.cache.EhCacheProvider 

       
       true
       
       
       true
       
       
       true
       
       
       
       true 
       
        
         
         
         
    


ehcache.xml:


   

    

     
    
           
    
     
     
     
    

    
    
    
	
	
	



Test.java:

package basicCar;

import java.sql.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


import eventListener.MyLoadListener;
import eventListener.MyPreInsertListener;



import basicCar.bean.Address;
import basicCar.bean.Alias;
import basicCar.bean.BasicCar;
import basicCar.bean.Salesman;
import basicCar.bean.CarOrder;


public class Test {

	Configuration cfg;

	SessionFactory sf;

	Session session;

	public static void main(String[] args) {
		Test test = new Test();
		test.doConfiguration();
		test.openSession();

		//test.saveEntity();
		test.updateEntity();
		//test.queryEntity3();
		// test.deleteEntity();

		test.closeSession();
		System.out.println("end");
	}

	void doConfiguration() {
		cfg = new Configuration();	
		//实现监听器
		/*MyLoadListener mll = new MyLoadListener();
		MyPreInsertListener mpl = new MyPreInsertListener();
		cfg.setListener("load", mll);*/
		//cfg.setListener("pre-inset",mpl);
		
		cfg.configure();
		sf = cfg.configure().buildSessionFactory();

		
	}

	// open session from session factory
	void openSession() {
		session = sf.openSession();
	}

	// close session
	void closeSession() {
		session.close();
	}

	// save a BasicCar in database
	void saveEntity() {
		// begin a transaction to save
		Transaction tx1 = session.beginTransaction();
		/*
		 * Salesman sc = new Salesman(); sc.setSalesname("aaa"); CarOrder co =
		 * new CarOrder(); co.setcarname("dd"); co.setSalesman(sc); Set cs = new
		 * HashSet(); cs.add(co); sc.setCarorders(cs);
		 */
		Salesman sc = new Salesman("hello33");
		
		Address as = new Address("广东","茂名","鳌头","34号");
		
		Alias alia = new Alias();
		alia.setAliasName("dkfjk");
		

		CarOrder co1=new CarOrder();
		co1.setcarname("aa111");
		CarOrder co2=new CarOrder();
		co2.setcarname("aa112");

		Set carorders = new HashSet();
		carorders.add(co1);
		carorders.add(co2);
		
		sc.setAlias(alia);
		alia.setSalesman(sc);		
		
		co1.setSalesman(sc);
		co2.setSalesman(sc);
		sc.setCarOrders(carorders);
		sc.setAddress(as);
		
		session.save(sc);
		session.save(co1);
		session.save(co2);
		session.save(alia);
		
		
		/*Salesman sm1 = new Salesman("xiaox");
		Salesman sm2 = new Salesman("xiaox2");
		Salesman sm3 = new Salesman("xiaox3");
		
		BasicCar bc1 = new BasicCar("BB");
		BasicCar bc2 = new BasicCar("BB2");
		BasicCar bc3 = new BasicCar("BB3");

		Set salesmans = new HashSet();
		Set basiccars = new HashSet();
		
		salesmans.add(sm1);
		salesmans.add(sm2);
		salesmans.add(sm3);
		basiccars.add(bc1);
		basiccars.add(bc2);
		basiccars.add(bc3);
		
		sm1.setCars(basiccars);
		bc1.setSalesmans(salesmans);
		
		session.save(sm1);
		session.save(sm2);
		session.save(sm3);
		session.save(bc1);
		session.save(bc2);
		session.save(bc3);*/
		

		tx1.commit();
	}

	// delete a BasicCar in database
	/*
	 * void deleteEntity() { // delete the id=1 basicCar Object from database
	 * Transaction tx3 = session.beginTransaction(); try { BasicCar bc4 =
	 * (BasicCar) session.load(BasicCar.class, new Long(1));
	 * session.delete(bc4); } catch (Exception e) { System.out.println("id=1 car
	 * are not existed, can't be deleted"); } tx3.commit(); } // update a
	 * BasicCar in database void updateEntity() { // update "factory" and "name"
	 * of the id=1 basicCar Object in database Transaction tx2 =
	 * session.beginTransaction(); BasicCar bc2 = (BasicCar)
	 * session.load(BasicCar.class, new Long(1)); bc2.setFactory("ShangHai");
	 * bc2.setName("SHCar"); session.update(bc2); tx2.commit(); }
	 */
	
void updateEntity() {
		
		//测试乐观锁
		Session session1=sf.openSession();
		Session session2=sf.openSession();
		
		
		Transaction tx1 = session1.beginTransaction();
		Transaction tx2 = session2.beginTransaction();
		
		try{
		
			Alias ao1 = (Alias) session1.load(Alias.class, new Long(3));
			Alias ao2 = (Alias) session2.load(Alias.class, new Long(3));
		//这时候,两个版本号是相同的
		ao1.setAmoney(ao1.getAmoney()+10);
		tx1.commit();		
		//这时候,两个版本号是不相同的
		ao2.setAmoney(ao2.getAmoney()-10);
		tx2.commit();
		System.out.println("OK!");
		}catch(Exception e){
			System.out.println(e);
			if(tx2 != null)//有同步数据库的作用
			{
				tx2.rollback();
				//updateEntity2();
			}
			else if(tx1 != null)//有同步数据库的作用
			{
				tx1.rollback();
				//updateEntity2();
			}
			
		}finally{
			session1.close();
			session2.close();
		}
	}
	
    void updateEntity2() {
		//测试乐观锁
		Session session1=sf.openSession();		
		
		Transaction tx1 = session1.beginTransaction();
	
		try{		
			Alias ao1 = (Alias) session1.load(Alias.class, new Long(3));
	
		//重新执行该事务
		ao1.setAmoney(ao1.getAmoney()+10);
		tx1.commit();
		System.out.println("OK2!");
		}catch(Exception e){
			//System.out.println(e);
			if(tx1 != null)//有同步数据库的作用
			{
				tx1.rollback();
				updateEntity();
			}
			
		}finally{
			session1.close();
		}
		
    }


	  void queryEntity() 
	  {
		  Session session2 = sf.openSession();
 	      Query query2 = session2.createQuery("from Salesman");
 	 
         java.util.List list2 = query2.list();
		 
	     for(int i=0;i s1 = ac2.getCars() ;
	    		 if(s1!=null)
	    		 {
	    			 
			 		 for(Iterator it = s1.iterator(); it.hasNext();)
			 		 {
			 			 String name1 = ac2.getSalesname();
			 			System.out.print(name1+"拥有职务:");
			 			BasicCar r = (BasicCar) it.next() ;
			 			System.out.println("\t【"+r.getName()+"】");
			 		 }
	    		 }
		 		 
	    	 }    	 

	     }
 	       session2.close();	  
	  }
	  //queryEntity2和queryEntity3都还要在对类启用二级缓存
	  void queryEntity2() //对类对象进行缓存
		{
			
			 Session session1 = sf.openSession();
			
			 try{ 
			 Query query = session1.createQuery("from Salesman");
					
		     java.util.List list = query.list();
			 
		     for(int i=0;i 72");
			
			 //设置使用查询缓存
			 query.setCacheable(true);
			 query.setCacheRegion("basiCar.bean.Salesman");
			 
		     java.util.List list = query.list();
			 
		     for(int i=0;i 72");
	    	 
	    	//设置使用查询缓存
			 query2.setCacheable(true);                     //设置第二个查询是否使用第一个session的缓存
			 query2.setCacheRegion("basiCar.bean.Salesman");//缓存区域不同结果查询重新从数据库导入
	    	 
	         java.util.List list2 = query2.list();
			 
		     for(int i=0;i

数据库图:

hibernate annotation总结_第2张图片                hibernate annotation总结_第3张图片


hibernate annotation总结_第4张图片                                      hibernate annotation总结_第5张图片                              hibernate annotation总结_第6张图片


要导入的包:

hibernate annotation总结_第7张图片


最后:还有映射复合主键和继承关系映射没做,需要再补充。

你可能感兴趣的:(Hibernate)