Getting Started with Java [20]-hibernate Simple example

Source: Internet
Author: User

first, Hibernate Introduction

In many scenarios, we don't need to use JdbcTemplate to manipulate SQL statements directly, so we can use the ORM tool to save a lot of code and development Time. ORM tools can shift attention away from Error-prone SQL code to how to implement the real needs of the Application.

Spring's support for ORM frameworks provides an integration point with these frameworks as well as some additional services:

    • Support for integrated Spring declarative transactions;
    • Transparent exception handling;
    • A thread-safe, lightweight template class;
    • DAO Support class;
    • Resource Management.

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

ii. Examples of spring+hibernate1. Create a database table

MySQL creates a new database store, and then executes the following sql:

1 Create TableCategory (2Idint  not NULL,3Namevarchar( the)NULL,4 constraintPk_categoryPrimary Key(Id)5 );6 7 INSERT  intoCategory (id,name)VALUES(1,'Women');8 INSERT  intoCategory (id,name)VALUES(2,'Beauty Makeup');9 INSERT  intoCategory (id,name)VALUES(3,'Books');
Db_store.sql2. Code Structure

The IDE I'm using is ideaiu, which builds the project through MAVEN and configures spring through XML. The code structure after completion is:

3. Create entity class category
Class category{    private int cateid;    Private String catename;    Number of omitted Get,set method
@Override public String toString () { return "id=" +cateid+ "name=" +catename; }}

  

4. Modify the pom.xml, and introduce the relevant 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 "> <prope Rty name= "driverclassname" value= "com.mysql.jdbc.Driver" ></property> <property name= "url" value= "jdbc:m        Ysql://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=" CLASSP Ath:hibernate/hibernate.cfg.xml "/> </bean> <tx:annotation-driven/> <bean id=" TransactionManager "class=" org.springframework.orm.hibernate4.HibernateTransactionManager "> <property name=" SESSIONFAC Tory "ref=" sessionfactory "/> </bean> <bean id=" categorydao "class=" CategoryDao "> <construct Or-arg ref= "sessionfactory" ></constructor-arg> </bean></beans>

  

DataSource Nothing special, it is not explained. Look at the other points:

①hibernate sessionfactory:

The primary interface required to use Hibernate is the Org.hibernate.session,session interface, which provides the most basic data access capabilities such as Crud. With Hibernate's session interface, the Application's repository can meet all of the persistence needs. The standard way to get Hibernate session objects is through the implementation class of the Hibernate sessionfactory interface.

In the Sessionfactory configuration, the main settings are two properties: datasource set up a data connection, configlocation set the path to hibernate configuration File.

② transactions

If database operations support transactions, you need to 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 is to support transactions, annotate @transactional is Required.

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 Cate        Gory 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. Testing
@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 ("menswear");    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 Address: Https://github.com/cathychen00/learnjava/tree/master/DemoHibernate

Getting Started with Java [20]-hibernate Simple example

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.