Hibernate is used to add, delete, modify, and query employee tables. hibernate employees

Source: Internet
Author: User

Hibernate is used to add, delete, modify, and query employee tables. hibernate employees
1.1 questions

Hibernate is used to add, delete, modify, and query employee tables.

1.2 Solution

Hibernate steps:

  1. Import the Hibernate package and the database driver package.
  2. Introduce the Hibernate. cfg. xml main configuration file.
  3. Create an object class.
  4. Create a ing file.
  5. Use common Hibernate APIs to perform addition, deletion, modification, and query operations.
Step 1

To implement this case, follow these steps.

 

Environment: myeclipse 6.5, mysql 5.0, and Hibernate 3.

 

Step 1: Prepare to create the employee table EMP. The table creation statement is as follows:

 

CREATE TABLE `emp` (  `ID` INT(4) NOT NULL AUTO_INCREMENT,  `NAME` VARCHAR(50) NOT NULL,  `AGE` INT(11) DEFAULT NULL,  `SALARY` DOUBLE(7,2) DEFAULT NULL,  `MARRY` CHAR(1) DEFAULT NULL,  `BIRTHDAY` DATE DEFAULT NULL,  `LAST_LOGIN_TIME` DATE DEFAULT NULL,  PRIMARY KEY (`ID`)) ENGINE=INNODB DEFAULT CHARSET=utf8

 

Create a WEB project named Hibernate.

Step 2: import the Hibernate Development Kit and the database driver package. The package structure of the project is as follows:

 

Net disk download jar package: http://yunpan.cn/cmRG5gzdMtGMX access password 3747

 

Step 3: Introduce the Hibernate main configuration file

Copy the Hibernate. cfg. xml file to the project and place it in the src root path. Configure the database connection information and Hibernate framework parameters in the master configuration file. The Code is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 

 

Step 4: Create an object class

Create the package com. souvc. entity and create the entity class Emp. java corresponding to the employee table under the package. The Code is as follows:

package comsouvc.entity;import java.sql.Date;import java.sql.Timestamp;public class Emp {    private Integer id;    private String name;    private Integer age;    private Double salary;    private Boolean marry;    private Date birthday;    private Timestamp lastLoginTime;    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 Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    public Double getSalary() {        return salary;    }    public void setSalary(Double salary) {        this.salary = salary;    }    public Boolean getMarry() {        return marry;    }    public void setMarry(Boolean marry) {        this.marry = marry;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    public Timestamp getLastLoginTime() {        return lastLoginTime;    }    public void setLastLoginTime(Timestamp lastLoginTime) {        this.lastLoginTime = lastLoginTime;    }}

 

 

Step 5: Create a ing File

In com. souvc. under the entity package, create a ing file for the employee entity class named Emp. hbm. xml, and configure the relationship between object classes and tables in the file, and the relationship between attributes in the class and fields in the table. The Code is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

 

 

Step 6: declare the ing File

In the main configuration file hibernate. cfg. xml, declare the ing relationship file Emp. hbm. xml. The Code is as follows:

<! -- Declare the ing relationship file --> <mapping resource = "com/souvc/entity/Emp. hbm. xml"/>

 

The complete code is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 

 

Step 7: Create a Session Tool

Create the HibernateUtil tool class to create Session objects. The Code is as follows:

Package com. souvc. util; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. cfg. configuration; public class HibernateUtil {private static SessionFactory sessionFactory; static {// load the Hibernate main Configuration file Configuration conf = new Configuration (); conf. configure ("/hibernate. cfg. xml "); sessionFactory = conf. buildSessionFactory ();}/*** create session */public static Session getSession () {return sessionFactory. openSession ();} public static void main (String [] args) {System. out. println (getSession ());}}

 

 

Output result:

SessionImpl (PersistenceContext [entityKeys = [], collectionKeys = []; actionQueue [insertions = [] updates = [] deletions = [] collectionCreations = [] collectionRemovals = [] collectionUpdates = [])

 

Step 8: Use Hibernate to add, delete, modify, and query employee tables.

Create the com. souvc. test package, create a JUNIT test class under the package, and use Hibernate in the class to write the method for adding, deleting, modifying, and querying the EMP table. The Code is as follows:

 

Package com. souvc. test; import java. SQL. date; import java. SQL. timestamp; import java. util. list; import org. hibernate. hibernateException; import org. hibernate. query; import org. hibernate. session; import org. hibernate. transaction; import org. junit. test; import com. souvc. util. hibernateUtil; import comsouvc. entity. emp;/*** demonstrate the basic usage of Hibernate */public class TestEmp {/*** add emp */@ Test public void add () {// simulate the emp Emp e = new Emp (); e. setName ("ggg"); e. setAge (29); e. setMarry (false); e. setSalary (1, 8000.00); e. setBirthday (Date. valueOf ("1983-10-20"); e. setLastLoginTime (new Timestamp (System. currentTimeMillis (); // obtain the session Session session = HibernateUtil. getSession (); // enable Transaction ts = session. beginTransaction (); try {// execute the new session. save (e); // submit the transaction ts. commit ();} catch (HibernateException e1) {e1.printStackTrace (); // roll back the transaction ts. rollback ();} finally {session. close () ;}/ *** query emp by ID */@ Test public void findById () {Session session = HibernateUtil. getSession (); Emp emp = (Emp) session. get (Emp. class, 1); System. out. println (emp. getName (); System. out. println (emp. getBirthday (); System. out. println (emp. getLastLoginTime (); session. close ();}/*** modify emp */@ Test public void update () {Session session = HibernateUtil. getSession (); // query the data Emp emp = (Emp) session to be modified. get (Emp. class, 1); // enable Transaction ts = session. beginTransaction (); try {// simulate emp data modification. setName ("ee"); emp. setAge (20); // execute the modify session. update (emp); // submit the transaction ts. commit ();} catch (HibernateException e) {e. printStackTrace (); // roll back the transaction ts. rollback ();} finally {// close the connection session. close () ;}/ *** delete emp */@ Test public void delete () {Session session = HibernateUtil. getSession (); Emp emp = (Emp) session. get (Emp. class, 1); Transaction ts = session. beginTransaction (); try {session. delete (emp); ts. commit ();} catch (HibernateException e) {e. printStackTrace (); ts. rollback ();} finally {session. close () ;}/ *** query all emp */@ Test public void findAll () {String hql = "from Emp"; Session session = HibernateUtil. getSession (); Query query = session. createQuery (hql); List <Emp> emps = query. list (); for (Emp e: emps) {System. out. println (e. getName ();} session. close ();}}

 

Added:

 

Query by id:

 

Query all:

 

Update:

 

Delete:

 

Tip: note that the database must have data with id 1 before you can operate the data. Id based on the data in the user.

Source code is as follows: http://yunpan.cn/cmR97XCh6SvB6 access password afb4

 

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.