One-way, multiple-to-one hibernate

Source: Internet
Author: User

For example, the relationship between provinces and cities

Province. java

package www.csdn.net.blank.bean;import java.io.Serializable;public class Province  implements Serializable{/** *  */private static final long serialVersionUID = 1L;private Integer id;private String name;public Province() {super();// TODO Auto-generated constructor stub}public Province(Integer id, String name) {super();this.id = id;this.name = name;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}

City. java

package www.csdn.net.blank.bean;import java.io.Serializable;public class City implements Serializable{    /** *  */private static final long serialVersionUID = 1L;private Integer id;        private String  name;        private Province province;public City() {super();// TODO Auto-generated constructor stub}public City(Integer id, String name) {super();this.id = id;this.name = name;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Province getProvince() {return province;}public void setProvince(Province province) {this.province = province;}    }

Provice configuration file Provice. hbm. xml

 
 
  
   
    
    
   
   
  
 

City. hbm. xml

 
 
  
   
    
    
   
      
   

// Use Hibernate Element to map multiple-to-one associations

Features-to-one attributes:

* Name: Specifies the name of the persistent class to be mapped.

* Column: Set the foreign key of the table corresponding to the persistence class attribute.

* Class: Set the attribute type of the persistence class.

* Not-null: whether to allow null.


Hibernate encapsulates the BaseDao interface for addition, deletion, query, and modification

Package www.csdn.net. blank. dao; import java. io. serializable; import java. util. list; @ SuppressWarnings ("rawtypes") public interface BaseDao {/*** save Object ** @ param entity */public void saveObject (Object entity ); /*** update Object ** @ param entity */public void updateObject (Object entity ); /*** Delete Object ** @ param entity */public void deleteObject (Object entity ); /*** Delete object objects by id ** @ param clazz * @ param id */public void deleteObjectById (Class clazz, Serializable id ); /*** query Object objects by id ** @ param clazz * @ param id * @ return */public Object loadObjectById (Class clazz, Serializable id ); /*** query Object objects by id ** @ param clazz * @ param id * @ return */public Object getObjectById (Class clazz, Serializable id ); /*** query all operations ** @ param clazz * @ return */public List getObjects (Class clazz );}

BaseDaoImpl

Package www.csdn.net. blank. dao. impl; import java. io. serializable; import java. util. arrayList; import java. util. list; import org. hibernate. session; import org. hibernate. transaction; import www.csdn.net. blank. dao. baseDao; import www.csdn.net. blank. util. required; @ SuppressWarnings ("rawtypes") public class BaseDaoImpl extends implements BaseDao {@ Overridepublic void saveObject (Object entity) {// obtain the session Object Session = getSessionObject (); // open the Transaction ts = session. beginTransaction (); try {// Save the session. save (entity); // submit the transaction ts. commit ();} catch (Exception e) {ts. rollback () ;}@ Overridepublic void updateObject (Object entity) {// obtain the session Object Session session = getSessionObject (); // open the Transaction ts = session. beginTransaction (); try {// Save the session. update (entity); // submit the transaction ts. commit ();} catch (Exception e) {ts. rollback () ;}@ Overridepublic void deleteObject (Object entity) {// obtain the session Object Session session = getSessionObject (); // open the Transaction ts = session. beginTransaction (); try {// Save the session. delete (entity); // submit the transaction ts. commit ();} catch (Exception e) {ts. rollback () ;}@ Overridepublic void deleteObjectById (Class clazz, Serializable id) {// obtain the session object Session session = getSessionObject (); // open the Transaction ts = session. beginTransaction (); try {// Save the session. delete (getObjectById (clazz, id); // submit the transaction ts. commit ();} catch (Exception e) {ts. rollback () ;}@ Overridepublic Object loadObjectById (Class clazz, Serializable id) {return null ;}@ Overridepublic Object getObjectById (Class clazz, Serializable id) {Object obj = null; session session = getSessionObject (); Transaction ts = session. beginTransaction (); try {obj = session. get (clazz, id); ts. commit ();} catch (Exception e) {ts. rollback ();} finally {session. close () ;}return obj ;}@ Overridepublic List getObjects (Class clazz) {List list = new ArrayList (); Session session = getSessionObject (); Transaction ts = session. beginTransaction (); try {list = session. createQuery ("from" + clazz. getName ()). list (); ts. commit ();} catch (Exception e) {ts. rollback () ;}return list ;}}

Hibernate-encapsulated tool class HiberUtil. java

Package www.csdn.net. blank. util; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. boot. registry. standardServiceRegistryBuilder; import org. hibernate. cfg. configuration; import org. hibernate. service. serviceRegistry; public class HiberUtil {static Configuration cfg; static ServiceRegistry serviceRegistry; static SessionFactory sessionFactory; static {// create a Configuration object call. configure () method, default class/hibernate. cfg. xmlcfg = new Configuration (). configure (); // create a service object serviceRegistry = new StandardServiceRegistryBuilder (). applySettings (cfg. getProperties ()). build (); // create sessionFactory factory sessionFactory = cfg. buildSessionFactory (serviceRegistry);}/*** get the session object * @ return */public static Session openSession () {return sessionFactory. openSession ();}}
Hibernate. cfg. xml

 
 
  
   
   
    
Com. mysql. jdbc. Driver
   
   
   
    
Jdbc: mysql: // localhost: 3306/jd2? UseUincode = true & characterEncoding = UTF-8
   
   
   
    
Root
   
   
   
    
Root
   
   
   
    
Org. hibernate. dialect. MySQLDialect
   
   
   
    
Thread
   
   
   
    
True
   
   
   
    
False
   
   
   
    
Update
   
   
   
   
  
 

Test class

Package www.csdn.net. blank. junit; import org. junit. test; import www.csdn.net. blank. bean. city; import www.csdn.net. blank. bean. province; import www.csdn.net. blank. dao. baseDao; import www.csdn.net. blank. dao. impl. baseDaoImpl; import www.csdn.net. blank. util. hiberUtil; public class Test1 {@ Testpublic void test () {HiberUtil. openSession ();} private BaseDao baseDao = new BaseDaoImpl (); @ Testpublic void save () {Province Province = new Province (); province. setName ("HEBEI 1"); City entity = new City (); entity. setName ("Shijiazhuang"); entity. setProvince (province); baseDao. saveObject (entity) ;}@ Testpublic void update () {City entity = (City) baseDao. getObjectById (City. class, 2); if (entity! = Null) {System. out. println (entity. getName ();} else {System. out. println ("xxxx ");}}}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.