您的位置:首页 > 编程语言 > Java开发

Spring基本使用:整合hibernate

2014-05-28 15:51 465 查看
一、xml中配置数据源:
<!-- 配置数据源dataSource -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:jdbc.properties"/>
</bean>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

其中,jdbc.properties中取出具体的配置数据,dataSource成为了spring的一个bean。

二、配置Hibernate的SessionFactory:

<!--Hibernate的SessionFactory 的配置 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ustcinfo.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>又配置了一个spring的bean,实现了原本的hibernate.cfg.xml文件中的配置。属性中包括:
1.注入了dataSource这个bean,完成数据源配置;

2.属性“annotatedClasses”展示了和数据库配对的User类,并且用list标签包括,说明可以有很多很多其他类;

3.属性“hibernateProperties”中的props配置数据连接的一些参数,如方言等。

三、对model类添加注解,(不用在model层中添加source.hbm.xml的配置文件)

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {
private int id;
private String username;
private String password;

@Id
@GeneratedValue
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;
}
}

四、将配置好的sessionFactory这个bean稳稳地注入所需要使用的实现类中。
import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.stereotype.Component;

import com.ustcinfo.dao.UserDao;
import com.ustcinfo.model.User;
@Component
public class UserDaoImpl implements UserDao{
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void save(User user){
Session s = sessionFactory.openSession();
s.beginTransaction();
s.save(user);
s.getTransaction().commit();
}
}五、开心的使用实现类中的方法:
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserService userService =(UserService) ctx.getBean("userServiceImpl");
User user = new User();
userService.mySave(user);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: