1.导入jar包(Spring、hibernate的jar包,以及连接操作mysql数据库的jar包)
2.写一个User的Bean实体类(属性参数有id,name,生成set、get以及toString方法),并生成该类的映射文件(将id修改为自增长<generator class="increment" />),生成hibernate的配置文件hibernate.cfg.xml;
<hibernate-configuration>
<session-factory >
<!-- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">258</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property> -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="org/hp/bean/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3.写Spring的配置文件test.xml。
Spring对Hibernate的整合,是在applicationContext.xml(test.xml)中配置sessionFactory来实现的,其中sessionFactory中要装配dataSource。这个类适用于配置基本类型的数据库连接,如果要想进行多数据源,那么该Bean对应的java类就要用DynamicDataSource。(如不理解百度看下
Spring中dataSourse配置详解哦)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="password" value="258"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
4.写一个测试类(我们可以去查询id=1的数据),打开mysql数据库的服务。
package org.hp.test;
import org.hp.bean.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate5.HibernateTemplate;
import com.sun.xml.internal.bind.CycleRecoverable.Context;
public class Shtest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("test.xml");
HibernateTemplate hibernateTemplate = (HibernateTemplate) context.getBean("hibernateTemplate");
User user = hibernateTemplate.get(User.class, 1);
System.out.println(user);
}
}
运行Shtest测试类,就可以看到我们的打印结果啦!!!如下图