Hibernate学习1--SpringMVC+Hibernate集成环境搭建

除了刚毕业那会用了几个月的hibernate好像好久都没有碰过了,正好最近在整理以前的学习笔记就把这块知识系统的学习一下,特别是hibernate和ibatis的对比应该对我现在做的东西有很大的帮助。

这个博客可能会是一个系列,今天是第一篇,搭建环境篇。由于以前的环境是springmvc+maven的环境,所以本系列博客就采用springmvc+hibernate的环境。

1 maven环境的jar包依赖,我这里采用的是spring3.2.2的版本和Hibernte的4.2.0的版本(pom.xml)

 <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 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)

 <!--配置数据源-->
    <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>

对应的表结构为

Hibernate学习1--SpringMVC+Hibernate集成环境搭建_第1张图片

5 Student的DO和相关DAO实现如下(Student.java,StudentDAO.java)

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)

@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这么流行,其功能不可能只有这些,以后我们会探讨一些更深入的知识。

另外 下面这两句的配置会在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



你可能感兴趣的:(Hibernate学习1--SpringMVC+Hibernate集成环境搭建)