JAVA入門[20]-Hibernate簡單樣本

來源:互聯網
上載者:User

標籤:tor   date()   注意力   final   autowired   管理   java   date   依賴   

一、Hibernate簡介

在很多情境下,我們不需要使用JdbcTemplate直接操作SQL語句,這時候可以用ORM工具來節省數大量的的代碼和開發時間。ORM工具能夠把注意力從容易出錯的SQL代碼轉向如何?應用程式的真正需求。

Spring對ORM架構的支援提供了與這些架構的整合點以及一些附加的服務:

  • 支援整合Spring聲明式事務;
  • 透明的異常處理;
  • 安全執行緒的、輕量級的模板類;
  • DAO支援類;
  • 資源管理。

Hibernate是在開發人員社區很流行的開源ORM架構。

二、Spring+Hibernate執行個體1.建立資料庫表

mysql建立資料庫store,然後執行如下sql:

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,‘女裝‘);8 INSERT INTO category(id,Name) VALUES (2,‘美妝‘);9 INSERT INTO category(id,Name) VALUES (3,‘書籍‘);
db_store.sql2.代碼結構

我用的IDE是IdeaIU,通過maven構建項目,通過xml配置spring。完成後的代碼結構為:

3.建立實體類Category
class Category{    private int cateId;    private String cateName;    //次數省略get,set方法
@Override public String toString() { return "id="+cateId+" name="+cateName; }}

  

4.修改pom.xml,引入相關依賴。
<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.配置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沒什麼特別的,就不在解釋了。看下其他幾點:

①hibernate sessionFactory:

使用Hibernate所需的主要介面是org.hibernate.Session,Session介面提供了CRUD等最基本的資料訪問功能。通過Hibernate的Session介面,應用程式的Repository能夠滿足所有的持久化需求。而擷取Hibernate Session對象的標準方式是藉助於Hibernate SessionFactory介面的實作類別。

在sessionFactory配置主要設定了兩個屬性:dataSource設定了資料連線,configLocation設定了hibernate設定檔的路徑。

②事務

要是資料庫操作支援事務,需要配置<tx:annotation-driven/>和transactionManager。

6.hibernate配置

①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"><hibernate-configuration><session-factory>    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>    <property name="show_sql">true</property>    <mapping resource="hibernate/Category.hbm.xml"/></session-factory></hibernate-configuration>

  

②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"><hibernate-mapping>    <class name="Category" table="Category">        <id name="cateId" column="id">            <generator class="native"/>        </id>        <property name="cateName" column="name"/>    </class></hibernate-mapping>

  

7.資料訪問實作類別CategoryDao

如果方法要支援事務,需要加註解@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.測試
@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("母嬰");        categoryDao.save(category);    }    @Test    public void testUpdate() {        Category category = new Category();        category.setCateId(4);        category.setCateName("男裝");        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);    }}

  

源碼地址:https://github.com/cathychen00/learnjava/tree/master/DemoHibernate

 

JAVA入門[20]-Hibernate簡單樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.