JAVA beginners [20]-simple example of Hibernate, java-hibernate

Source: Internet
Author: User

JAVA beginners [20]-simple example of Hibernate, java-hibernate
1. Introduction to Hibernate

In many scenarios, you do not need to use JdbcTemplate to directly operate SQL statements. At this time, you can use the ORM tool to save a lot of code and development time. The ORM tool can shift the focus from error-prone SQL code to how to implement the real needs of applications.

Spring's support for the orm framework provides integration points with these frameworks and some additional services:

  • Supports Spring declarative transactions;
  • Transparent exception handling;
  • Thread-safe, lightweight template class;
  • DAO Support class;
  • Resource Management.

Hibernate is an open source ORM framework that is very popular in the developer community.

Ii. Spring + Hibernate instance 1. Create a database table

Create a database store in mysql and run the following SQL statement:

1 create table Category (2 Id int not null, 3 Name varchar (80) null, 4 constraint pk_category primary key (Id) 5); 6 7 insert into category (id, Name) VALUES (1, 'female'); 8 insert into category (id, Name) VALUES (2, 'makeup '); 9 insert into category (id, Name) VALUES (3, 'book ');Db_store.sql2. code structure

The ide I use is IdeaIU. I build a project through maven and configure spring through xml. The code structure after completion is:

Class Category {private int cateId; private String cateName; // The number of times the get or set method is omitted.
@ Override public String toString () {return "id =" + cateId + "name =" + cateName ;}}

  

4. Modify pom. xml to introduce related dependencies.
<dependencies>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.12</version>        </dependency>        <dependency>            <groupId>org.hibernate</groupId>            <artifactId>hibernate-core</artifactId>            <version>4.3.5.Final</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.30</version>        </dependency>    </dependencies>

  

5. Configure applicationContext. xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>        <property name="url" value="jdbc:mysql://localhost:3306/store"></property>        <property name="username" value="root"></property>        <property name="password" value="root"></property>    </bean>    <bean id="sessionFactory"          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">        <property name="dataSource" ref="dataSource"/>        <property name="configLocation" value="classpath:hibernate/hibernate.cfg.xml"/>    </bean>    <tx:annotation-driven/>    <bean id="transactionManager"          class="org.springframework.orm.hibernate4.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory"/>    </bean>    <bean id="categoryDao" class="CategoryDao">        <constructor-arg ref="sessionFactory"></constructor-arg>    </bean></beans>

  

DataSource is nothing special, so I will not explain it. Take a look at the following points:

① Hibernate sessionFactory:

The main interface required by Hibernate is org. hibernate. Session. The Session interface provides CRUD and other basic data access functions. Through the Hibernate Session interface, the Repository of the application can meet all persistence requirements. The standard way to obtain the Hibernate Session object is through the Implementation class of the Hibernate SessionFactory interface.

The sessionFactory configuration mainly sets two attributes: dataSource sets the data connection and configLocation sets the path of the hibernate configuration file.

② Transactions

If database operations support transactions, you must configure <tx: annotation-driven/> and transactionManager.

6. hibernate Configuration

① Hibernate. cfg. xml

<?xml version='1.0' encoding='utf-8'?>        <!DOCTYPE hibernate-configuration PUBLIC                "-//Hibernate/Hibernate Configuration DTD 3.0//EN"                "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

  

② Category. hbm. xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

  

7. Data Access Implementation class CategoryDao

If the method supports transactions, add the annotation @ Transactional.

public class CategoryDao {    private SessionFactory sessionFactory;    public CategoryDao(SessionFactory sessionFactory) {        this.sessionFactory = sessionFactory;    }    private Session currentSession() {        return sessionFactory.getCurrentSession();    }    @Transactional    public void save(Category category) {        currentSession().save(category);    }    @Transactional    public void update(Category category){        currentSession().update(category);    }    @Transactional    public void delete(int id) {        Query query = currentSession().createSQLQuery("DELETE FROM category WHERE Id=::ID");        query.setInteger("::ID", id);        query.executeUpdate();    }    @Transactional    public int count() {        return getAll().size();    }    @Transactional    public Category getById(int id) {        Criteria criteria=currentSession().createCriteria(Category.class);        criteria.add(Restrictions.eq("id",id));        return (Category) criteria.uniqueResult();    }    @Transactional    public List<Category> getAll() {        return currentSession().createCriteria(Category.class).list();    }}

  

8. Test
@ ContextConfiguration (locations = "classpath: applicationContext. xml ") @ RunWith (SpringJUnit4ClassRunner. class) public class testCategoryDao {@ Autowired private CategoryDao categoryDao; @ Test public void testAdd () {Category category = new Category (); category. setCateId (4); category. setCateName ("Mother and Baby"); categoryDao. save (category) ;}@ Test public void testUpdate () {Category category = new Category (); category. setCateId (4); category. setCateName ("men's wear"); categoryDao. update (category) ;}@ Test public void testGetById () {int id = 4; Category category = categoryDao. getById (id); if (category = null) {System. out. println ("not exist");} else {System. out. println (category. toString () ;}@ Test public void testGetAll () {List <Category> categories = categoryDao. getAll (); for (Category item: categories) {System. out. println (item) ;}@ Test public void testCount () {int count = categoryDao. count (); System. out. println (count) ;}@ Test public void testDelete () {int id = 4; categoryDao. delete (id );}}

  

Source Code address: https://github.com/cathychen00/learnjava/tree/master/DemoHibernate

 

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.