Learn Hibernate notes

Source: Internet
Author: User
Tags object object

Before learning Java, the beginning of learning hibernate, at that time always feel ssh very tall, so I hurried to see the relevant video. However, because the actual need is not high, so the last hibernate component has not been used. Now a year has passed, also crazy learning Java for some time, did a few small projects, but finally to Java some understanding. Now in the work, the company is using SSH, so these two days again began to play hibernate. This study uses editplus directly and develops directly. See the official website of the demo, found that English is not so difficult to imagine. Haha, write down your own study. Here are the main records of three areas:

1. How to build Hibernate

2. Several common mapping relationships (One-to-one,one-to-many, Many-to-one, Many-to-many)


Setting up hibernate (directly using a text editor)

The first step: This process is not complex, mainly download to hibernate related jar package, and then the necessary jar into the classpath, specifically what is classpath, we can Baidu under. If you do not import into classpath, you will see an exception that cannot be found for the class. Why does this happen? Everyone can Baidu under the Java class loading process.

Step two: Write the Hibernate.cfg.xml file. This people do not have to hand-written, go directly to hibernate article copy one can. Here's My Code

<?xml version= ' 1.0 ' encoding= ' utf-8 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hiberna Te.org/dtd/hibernate-configuration-3.0.dtd ">

Import Java.io.*;import org.hibernate.*;import org.hibernate.cfg.*;/** * That's a hibernate config util * */public class hibernateconfigurationutil{    private static Hibernateconfigurationutil singleton = new Hibernateconfigurationutil ("Hibernate.cfg.xml");    private static sessionfactory factory;/** * Singleton pattern * */private hibernateconfigurationutil (String configxml) { C2/>init (Configxml);}    public void init (String configxml) {     Configuration cfg = new Configuration (). Configure (New File ("Hibernate.cfg.xml") )); Factory = Cfg.buildsessionfactory ();   Build the Session Factory} public    static Sessionfactory getsessionfactory () {    if (factory = = null) return Null;r Eturn Factory;}    /** * Open a new session * * */public static session opensession () {    Session session = Factory.opensession (); return ses sion;}}

Note that this class uses a singleton design pattern, because hibernate builds are time-consuming to start the configuration, and this object cannot be changed after startup, so each project starts once.

The third step: Write Basehibernatedao, this class note is encapsulated the save, delete, update, load four methods.

Import Java.io.*;import org.hibernate.*;import org.hibernate.cfg.*;/** * That's the base hibernate DAO, * it define a ser ies of method to access database * If you want to ' delete, update a object, the object must exists in Hibernate memery ' *  * @author Luohong * @date 2014-08-07 * */public class Basehibernatedao{public Basehibernatedao () {}/** * try to save a Object * */public void Save (Object object) {Session session = Hibernateconfigurationutil.opensession ();//Open Transac Tiontransaction transaction = Session.begintransaction (); Session.save (object);//Commint Transactiontransaction.commit ();} /** * Try to update a object * */public void Update (Object object) {Session session = Hibernateconfigurationutil.opense Ssion ();//Open transactiontransaction transaction = Session.begintransaction (); Session.update (object);//Commint        Transactiontransaction.commit ();} /** * Try to delete a object * */public void Delete (Object object) {Session session = HibernateconfigurationutIl.opensession ();//Open transactiontransaction transaction = Session.begintransaction (); Session.delete (object);//    Commint transactiontransaction.commit ();}  /** * Try to load a object from the database by ClassName and ID * */public object Load (class<?> className, Serializable        ID) {Session session = Hibernateconfigurationutil.opensession (); There is no need for Transactionreturn session.load (className, id);}}

Note: In save, update, delete method, only transaction is used to turn on the transaction, otherwise the database cannot find the related record.

Fourth step: After the here, it is very simple, only the specific class, the expansion of Basehibernatedao can be. Here is a one-to-many example. Simulation Scenario: The user has multiple addresses (address) first given two classes:

Import java.util.*;p ublic class user{private int id;private string password;private string name;    Private set<address> addressset;public void Setaddressset (set<address> addressset) {    This.addressSet = AddressSet;} Public set<address> Getaddressset () {    return addressset;} public void SetName (String name) {    this.name = name;} Public String GetName () {    return name;} public void setId (int id) {    this.id = ID;} public int getId () {    return ID;} public void SetPassword (String password) {    this.password = password;} Public String GetPassword () {    return password;} Public String toString () {    return "id =" + id + ", name =" + name + ", password =" + password + ", AddressSet =" + AddressSet;}}

/** * is the user address * A user has many address, but a adress belong to a user * It is the classical 1 * n Relat Ionship * @author Luohong * @date 2014-08-07 * */public class Address {//=====================properties================= ============ private int id; Private User belongto; Private String Code; Private String City; Private String Street; Private String Homenumber;//===================setter and getter======================== public void setId (int id) {th Is.id = ID; } public int getId () {return ID;} /* public void setbelongto (user user) {this.belongto = belongto,} public User getbelongto () {return belongto;} */public void Setcode (String code) {This.code = code,} public String GetCode () {return code,} public void Setci Ty (String city) {this.city = city,} public String getcity () {return city,} public void Sethomenumber (string home Number) {this.homenumber = Homenumber;} public String Gethomenumber () {return homenumber;} publIC string Getstreet () {return street;} public void Setstreet (String street) {this.street = Street;} ========================tostring================================ public String toString () {return ' id = ' + id + ', City = "+ City +", street = "+ Street +", Homenumber = "+ Homenumber +", code = "+ code;//+", belongto = "+ Bel Ongto; }       }

Give the relevant user.xml, address.xml; This example uses a one-way pair.

<?xml version= "1.0"?>  <! DOCTYPE hibernate-mapping public          "-//hibernate/hibernate mapping DTD 3.0//en"          "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">  

<?xml version= "1.0"?>  <! DOCTYPE hibernate-mapping public          "-//hibernate/hibernate mapping DTD 3.0//en"          "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">  


Then write a Userdao, inherit the Basehibernatedao, also very simple, haha, a look on to understand, this is Hibernate's great place.

Import java.util.*;import org.hibernate.*;/** * User DAO extends Basehibernatedao * can add new functions to the Custo  M DAO * * *  @author luohong * @date 2014-08-07 * */public class Userdao extends basehibernatedao{    /** * Delete A user by userId * */public void Deletebyid (String id) {if (id = = null) return;  Do nothingstring hql = "Delete User where id=?"; /1 Open Session session Session    = Hibernateconfigurationutil.opensession ();//2 Create a Queryquery query = session. CreateQuery (HQL);//3 Set the parameter to Queryquery.setstring (1, id);//4 execute queryquery.executeupdate ();}    /** * Find all user from database * */public list<user> findallusers () {    String hql = ' from user '; Session session = Hibernateconfigurationutil.opensession (); Query query = session.createquery (HQL); List userlist = Query.list (); return (list<user>) userlist;}}

The rest is the test, come on ...

Import java.io.*;import java.util.*;/** * Hibernate ORM Framework Demo * @author Luohong * @date 2014-08-06  *  * */public C Lass hibernatedemo{public static void Main (string[] args) throws exception{    Userdao Userdao = new Userdao ();        User user = new user (), User.setname ("Luohong"), User.setpassword ("Luohong")        ; set<address> AddressSet = new hashset<address> (); for (int i=0; i<3; i++) {Address address = new address (); ad Dress.setcode ("111"), Address.setcity ("Hongkang"), Address.setstreet ("Universal Street"), Address.sethomenumber (" a-2846 ");//address.setbelongto (user); Addressset.add (address);} User.setaddressset (AddressSet); userdao.save (user);}}





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.