一次性配置完成Spring与Hibernate,对一个刚开始学习的人来说,问题会出现很多。纵然侥幸配置成功了,后续估计也会出现很多问题。
所以今天决定抽丝剥茧。之前已经独立将hibernate和spring各组配置完成,现在,先从hibernate---->spring做起。
1、配置完成hibernate,他的文件不需要更改。此时,我将spring作为中间需要配置的东西。
比如,我要查询一张表,后续使用的时候,不想自己new,那么我就把操作表的这个类作为一个bean,交给spring来为我创建。
方法与spring第一个例子相同。这个方法可以有效的让我的类不杂乱,不需要修改这个操作类。只要配置成功,后续随时使用。
优点:配置成功,后续通过spring,随时使用。
一、现在开始编写要做为bean交由Spring管理的查询方法的类:
package duli;
import java.util.List;
import hibernate.factory.HibernateSessionFactory;
import org.hibernate.Session;
import org.hibernate.query.Query;
import bean.Customer;
//查询数据
public class CustomerDao {
public void queryCustomers(){
Session session = HibernateSessionFactory.getSession();
/**由会话创建一个session对象**/
Query query = session.createQuery("from bean.Customer");
List<Customer> list = query.list();
for (Customer lists : list) {
System.err.println(lists.getName());
}
}
public static void main(String[] args) {
new CustomerDao().queryCustomers();
}
}
二、在Spring配置文件applicationContext.xml:
<?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 先尝试将CustomerDao类配置到spring -->
<bean id="customerdao" class="duli.CustomerDao"></bean>
</beans>
三、测试类:
package bean.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import duli.CustomerDao;
//使用Spring配置的Bean
public class Test {
public static void main(String[] args) {
/*读取Spring配置文件,创建一个Bean工厂*/
@SuppressWarnings("resource")
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
/**读取Spring容器一个称为customerdao的bean,Spring容器自动创建对象实例**/
CustomerDao hbFactory = (CustomerDao)factory.getBean("customerdao");
hbFactory.queryCustomers();
}
}
通过以上三个步骤,已经将Bean配置到Spring。一步步深入,这个测试成功咱们再进行下一步。当然,上面这个配置,需要Hibernate的支撑,因为在CustomerDao里面,使用了Hibernate。具体内容:
Hibernate配置:
一、映射表的xml文件:Customer.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 package="bean" auto-import="false">
<!-- POJO类映射表及某表的关系-->
<class name="bean.Customer" table="customers" catalog="test">
<id name="customerID" type="java.lang.String">
<column name="customerID" length="8"/>
<generator class="assigned"></generator>
</id>
<!-- 映射表中name字段 -->
<property name="name" type="java.lang.String">
<column name="name" length="40"/>
</property>
<!-- 映射表中phone字段 -->
<property name="phone" type="java.lang.String">
<column name="phone" length="16"/>
</property>
</class>
</hibernate-mapping>
二、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>
<!-- 配置文件标签顺序property*,mapping*,(class-cache|collection-cache),event,listener* -->
<session-factory>
<!-- 设置访问mysql数据库的驱动描述 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 设置数据库的url -->
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property>
<!-- 指定登录数据库用户账户 -->
<property name="connection.username">root</property>
<!-- 指定登录数据库用户密码 -->
<property name="connection.password">123456</property>
<!-- 设置访问数据库的方言,提高数据库访问性能 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 设置ddl -->
<!-- <property name="hbm2ddl.auto">auto</property> -->
<!-- 配置控制台视图,显示查询内容 -->
<property name="show_sql">true</property>
<!-- 指出映射文件 -->
<mapping resource="resource/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
三、映射类:
package bean;
public class Customer {
private String customerID,name,phone;
public String getCustomerID() {
return customerID;
}
public void setCustomerID(String customerID) {
this.customerID = customerID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
四、会话工厂类:
package hibernate.factory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static String configfile = "resource/hibernate.cfg.xml";
/**ThreadLocal是一个本地线程**/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration config;
private static SessionFactory sessionFactory;
/**读取配置文件,创建一个工厂会话,这段代码为静态块,编译后已经运行**/
static{
try {
config = new Configuration().configure(configfile);
sessionFactory = config.buildSessionFactory();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**通过会话工厂打开会话,就可以访问数据库了**/
public static Session getSession(){
Session session = (Session)threadLocal.get();
if (session==null||!session.isOpen()) {
if (sessionFactory==null) {
rebuildSessionFactory();
}
session = (sessionFactory!=null)?sessionFactory.openSession():null;
}
return session;
}
/**重新创建一个会话工厂**/
public static void rebuildSessionFactory() {
try {
config.configure(configfile);
sessionFactory = config.buildSessionFactory();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**关闭与数据库的会话**/
public static void closeSession() {
Session session = (Session)threadLocal.get();
threadLocal.set(null);
if (session!=null) {
session.close();
}
}
}
在这些篇目里面,大量代码重复,我还写下来,是因为后续造成混乱,这样,完整的写完,后续参考时更容易找到问题,也能一目了然,在即使忘记的情况下,也能重新找到思路。
通过类似于复习的整合,是不是大概知道真正的整合,可以思考:
1、将这些数据通过依赖注入将数据注入。通过Spring创建Hibernate的会话工厂。
2、个人感觉,应该另外建一个Bean类,然后把现在的工厂类的变量或者方法交由该类。然后实现Spring。或者直接在现在的类上进行。但在Spring要做好控制。
3、根据搜索大概找到了原因:【不同类所工作的环境,影响到配置】