1. 程式人生 > >(9)spring4整合Hibernate5

(9)spring4整合Hibernate5

1.匯入spring 包和hibernate 包(hibernate中lib中的required(必備),以及jpa包)

2.匯入dbcp包和log4j(解析XML的)和commons-logging-1.2(Junit必備)

3.配置beans.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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 開啟Spring的Annotation支援 -->
	<context:annotation-config />
	<!-- 設定Spring 去哪些包中找Annotation -->
	<context:component-scan base-package="spring" />

    <!--Spring +Hibernate整合 -->
    <!--載入資料庫的連線配置檔案 -->
    <context:property-placeholder location="jdbc.properties"/>
    <!--配置資料庫來連線池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <!--驅動類全稱 -->
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <!--資料庫的url地址 -->
        <property name="url" value="${jdbc.url}" />
        <!--使用者名稱 -->
        <property name="username" value="${jdbc.username}" />
        <!--密碼 -->
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!--配置Hibernate的SessionFactory  -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <!--1、配置資料庫連線池  -->
    <property name="dataSource" ref="dataSource"></property>
    <property name="packagesToScan">
			<value>spring.model</value>
		</property>
    <!--2、Hibernate的配置資訊  -->
    <property name="hibernateProperties">
    <props>
    <!--方言  -->
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
    </props>
    </property>
    </bean>

<!--事物管理物件(session初始化(con,ps,rs)以及事務處理等) -->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

<!--配置事物的通知  -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!-- 事物的屬性,其實就是為切面中的哪些方法進行事物的配置 -->
        <tx:attributes>
        <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--aop配置資訊  -->
    <aop:config>
        <aop:pointcut id="pcut" expression="execution(* spring.dao.*.*(..))"/><!--一執行dao中所有類中的所有方法就進行事務處理  -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pcut"/>
    </aop:config>
</beans>

4.建立實體類:

@Entity
@Table(name="t_group")
public class Group {
private int id;
private String name;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}

}

@Entity
@Table(name="t_user")
public class User {
private int id;
private String username;
private String password;
private String nickname;
private Group group;


@ManyToOne
@JoinColumn(name="gid")
public Group getGroup() {
	return group;
}
public void setGroup(Group group) {
	this.group = group;
}
public User(String username, String password, String nickname) {
	super();
	this.username = username;
	this.password = password;
	this.nickname = nickname;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
	return id;
}

public void setId(int id) {
	this.id = id;
}
public String getUsername() {
	return username;
}
public void setUsername(String username) {
	this.username = username;
}
public String getPassword() {
	return password;
}
public void setPassword(String password) {
	this.password = password;
}
public String getNickname() {
	return nickname;
}
public void setNickname(String nickname) {
	this.nickname = nickname;
}
public User() {
}
@Override
public String toString() {
	return "User [id=" + id + ", username=" + username + ", password=" + password + ", nickname=" + nickname
			+ ", group=" + group + "]";
}



}

注意:(1).註釋(annotaion)統一寫在屬性上或者統一寫在get上,一定要統一,要不然會報Could not determine type for的錯誤

5.建立dao類

BaseDao:

public class BaseDao {
private SessionFactory SessionFactory;

	public SessionFactory getSessionFactory() {
	return SessionFactory;
}
@Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
	SessionFactory = sessionFactory;
}

protected Session getSession() {
	return SessionFactory.getCurrentSession();
}
}

注意:(1).此處使用建立SessionFactory然後注入的方法,以後我們會使用Template或者DaoSupport

(2).建立一個protected的getSession方法(只能子類呼叫),然後返回sessionFactory.getCurrentSession();

UserHibernateDao:

@Repository("userHibernateDao")//spring管理
public class UserHibernateDao extends BaseDao implements IUserDao {
private IGroupDao groupHibernateDao;
	
	
	
	public IGroupDao getGroupHibernateDao() {
		return groupHibernateDao;
	}
	@Resource//注入
	public void setGroupHibernateDao(IGroupDao groupHibernateDao) {
		this.groupHibernateDao = groupHibernateDao;
	}


	@Override
	public void update(User user) {
		// TODO 自動生成的方法存根
this.getSession().update(user);
	}

	@Override
	public void delete(int id) {
		// TODO 自動生成的方法存根
		this.getSession().delete(id);
	}

	@Override
	public User load(int id) {
		// TODO 自動生成的方法存根
		return this.getSession().load(User.class, id);;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> list(String sql, Object[] args) {
		// TODO 自動生成的方法存根
		Query<User> q=this.getSession().createQuery(sql);//通過session建立hql語句
		for(int i=0;i<args.length;i++) {
		q.setParameter(i, args[i]);//從0開始
		}
		List<User> list=q.list();
		return list;
	}

	@Override
	public void add(User user, int gid) {
		// TODO 自動生成的方法存根
		Group group=groupHibernateDao.load(gid);
		user.setGroup(group);
		getSession().save(user);
	}

}

GroupHibernateDao:

@Repository("groupHibernateDao")
public class GroupHibernateDao extends BaseDao implements IGroupDao {
//不能再注入UserHibernateDao,因為會相互注入,就會報錯,可以使用service分層解決
	@Override
	public void add(Group group) {
		// TODO 自動生成的方法存根
getSession().save(group);
	}

	@Override
	public Group load(int id) {
		// TODO 自動生成的方法存根
		return (Group)getSession().load(Group.class, id);
	}

}

注意:(1).該類不能再注入UserHibernateDao,因為會相互注入,就會報錯,可以使用service分層解決

6.測試類:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/beans.xml")
public class TestHibernate {
	@Resource(name="userHibernateDao")
	private IUserDao userHibernateDao;
	@Resource(name="groupHibernateDao")
	private IGroupDao groupHibernateDao;

	@Test
	public void test() {
	Group group=new Group();
	group.setName("test");
	groupHibernateDao.add(group);
	User user=new User("wukong", "123", "悟空");
	userHibernateDao.add(user, group.getId());
	}

}

注意:(1).出現NotClassDefFoundError就是少導包

(2).由於session關閉和延遲載入的原因,當session關閉不過需要再取資料時(延遲載入),就會報錯