Hibernate學習1--SpringMVC+Hibernate集成環境搭建

除了剛畢業那會用了幾個月的hibernate好像很久都沒有碰過了,正好最近在整理之前的學習筆記就把這塊知識系統的學習一下,特別是hibernate和ibatis的對比應該對我如今作的東西有很大的幫助。java

這個博客可能會是一個系列,今天是第一篇,搭建環境篇。因爲之前的環境是springmvc+maven的環境,因此本系列博客就採用springmvc+hibernate的環境。mysql

1 maven環境的jar包依賴,我這裏採用的是spring3.2.2的版本和Hibernte的4.2.0的版本(pom.xml)
web

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        
        <!-- hibernate start-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <!-- hibernate end-->

2 springMvc的配置(web.xml)spring

    <!--spring mvc 配置 start-->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--spring mvc 配置 end-->

3 Spring代理Hibernate的配置,正常來講,hibernate應該有本身的配置文件的,裏面配置數據源信息及hibernate的屬性設置,可是咱們使用了spring就能夠把相關配置放到spirng裏了。(spring-servlet.xml)sql

 <!--配置數據源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://XXXX:3306/zz_test"/>
        <property name="username" value="XXXX"/>
        <property name="password" value="XXXX"/>
    </bean>

    <!--配置hibernate-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mappingResources">
            <list>
                <value>com/XXX/test/hibernate/studentTest/Student.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <tx:annotation-driven transaction-manager="txManager"/>

4 接下來就是hibernate的業務配置文件了(Student.hbm.xml)
數據庫

<hibernate-mapping>
    <class name="com.XXX.test.hibernate.studentTest.Student" table="student1" schema="zz_test">
        <id name="id" type="java.lang.Integer" column="id">
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="16" />
        </property>
    </class>
</hibernate-mapping>

對應的表結構爲express

5 Student的DO和相關DAO實現以下(Student.java,StudentDAO.java)apache

public class Student implements Serializable {
    private Integer id;
    private String name;

    public Student() {
        super();
    }

    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;
    }
}

@Service
public class StudentDAO {

    @Autowired
    private SessionFactory sessionFactory;

    private Session session=null;

    public void init() {
        session = sessionFactory.openSession();
    }

    public void save(Student student) {
        Transaction tran = session.getTransaction();
        tran.begin();
        session.save(student);
        tran.commit();
    }

    public void update(Student student) {
        Transaction tran = session.getTransaction();
        tran.begin();
        session.update(student);
        tran.commit();
    }

    public void delete(Integer id) {
        String hql = "delete from Student o where o.id = ?";
        Transaction tran = session.getTransaction();
        tran.begin();
        Query query = session.createQuery(hql);
        query.setParameter(0, id);
        query.executeUpdate();
        tran.commit();
    }

    @SuppressWarnings("unchecked")
    public Student getModel(Integer id) {
        String hql = "from Student o where id = :id";
        Query query = session.createQuery(hql);
        query.setParameter("id", id);
        List list = query.list();
        if (list != null && list.size() == 1) {
            return (Student) list.get(0);
        } else {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public List getPagination(int maxResults, int firstResult) {
        String hql = "from Student o";
        Query query = session.createQuery(hql);
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResults);
        return query.list();
    }
}

6 前臺的調用方法以下(StudentController.java)session

@Controller
public class StudentController {

    @Autowired
    StudentDAO studentDAO;

    @RequestMapping(value = "/student/test.do" )
    public String test(HttpServletRequest request, HttpServletResponse response) {
        studentDAO.init();
        //添加
        for (int i = 0; i < 10; i++) {
            Student student = new Student();
            student.setName("Tao" + i);
            studentDAO.save(student);
        }
        //刪除
        studentDAO.delete(2);
        // 修改
        Student student = new Student();
        student.setId(4);
        studentDAO.update(student);
        // 單個查詢
        Student s = studentDAO.getModel(4);
        System.out.println(s.getName());
        // 分佈查詢
        List list = studentDAO.getPagination(4, 1);
        for (int i = 0; i < list.size(); i++) {
            Student std = (Student) list.get(i);
            System.out.println(std.getName());
        }
        return "success";
    }
}


總結一下,以上就是基本的運行環境了,之後的代碼都是在這個環境的基礎上進行展開。主要是maven的依賴,spring代理hibernate的配置及hibernate的DO和數據庫的映射。固然Hibernate這麼流行,其功能不可能只有這些,之後咱們會探討一些更深刻的知識。mvc

另外 下面這兩句的配置會在console端打印出相關的調用sql語句,對於代碼的調試有很大幫助。

   <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.format_sql">true</prop>

下面是一些其餘的hibernate屬性配置

         <!--數據庫鏈接池的大小-->
         <property name="hibernate.connection.pool.size">20</property>         
         
         <!--是否在後臺顯示Hibernate用到的SQL語句,開發時設置爲true,便於差錯,程序運行時能夠在Eclipse的控制檯顯示Hibernate的執行Sql語句。項目部署後能夠設置爲false,提升運行效率-->
         <property name="hibernate.show_sql">true</property>
         
         <!--jdbc.fetch_size是指Hibernate每次從數據庫中取出並放到JDBC的Statement中的記錄條數。Fetch Size設的越大,讀數據庫的次數越少,速度越快,Fetch Size越小,讀數據庫的次數越多,速度越慢-->
         <property name="jdbc.fetch_size">50</property> 
         
         <!--jdbc.batch_size是指Hibernate批量插入,刪除和更新時每次操做的記錄數。Batch Size越大,批量操做的向數據庫發送Sql的次數越少,速度就越快,一樣耗用內存就越大-->
         <property name="jdbc.batch_size">23</property> 
         
         <!--jdbc.use_scrollable_resultset是否容許Hibernate用JDBC的可滾動的結果集。對分頁的結果集。對分頁時的設置很是有幫助-->
        <property name="jdbc.use_scrollable_resultset">false</property>
         
         <!--connection.useUnicode鏈接數據庫時是否使用Unicode編碼-->
         <property name="Connection.useUnicode">true</property>
         
         <!--connection.characterEncoding鏈接數據庫時數據的傳輸字符集編碼方式,最好設置爲gbk,用gb2312有的字符不全-->
         <property name="connection.characterEncoding">gbk</property>


另外,dilletc是用來配置hibernte的方言的,咱們這裏用的是mysql因此按照以下配置,

 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

Hibenate的還支持如下方言



DB2 org.hibernate.dialect.DB2Dialect
DB2 AS/400 org.hibernate.dialect.DB2400Dialect
DB2 OS390 org.hibernate.dialect.DB2390Dialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
MySQL org.hibernate.dialect.MySQLDialect
MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle 9i/10g org.hibernate.dialect.Oracle9Dialect
Sybase org.hibernate.dialect.SybaseDialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect
Microsoft SQL Server org.hibernate.dialect.SQLServerDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Informix org.hibernate.dialect.InformixDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Ingres org.hibernate.dialect.IngresDialect
Progress org.hibernate.dialect.ProgressDialect
Mckoi SQL org.hibernate.dialect.MckoiDialect
Interbase org.hibernate.dialect.InterbaseDialect
Pointbase org.hibernate.dialect.PointbaseDialect
FrontBase org.hibernate.dialect.FrontbaseDialect
Firebird org.hibernate.dialect.FirebirdDialect
相關文章
相關標籤/搜索