日期:2014-05-19 浏览次数:20730 次
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost/spring_test" /> <property name="username" value="root" /> <property name="password" value="1234" /> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource" /> <property name="mappingResources"> <list> <value>com/xlinspace/www/entity/User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update javax.persistence.validation.mode=none </value> </property> </bean> <bean id="userDao" class="com.xlinspace.www.dao.UserDao"> <property name="sessionFactory" ref="mySessionFactory"></property> </bean>
public class UserDao { private HibernateTemplate ht = null; private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } private HibernateTemplate getHibernateTemplate(){ if(ht==null){ ht = new HibernateTemplate(getSessionFactory()); } return ht; } public Integer save(User user){ return (Integer)getHibernateTemplate().save(user); // Session session = getSessionFactory().getCurrentSession(); 实验不能这么取 // session.beginTransaction(); // session.save(user); // session.getTransaction().commit(); } }
public class UseUser { public static void main(String[] args){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = new User(); user.setAge(10); user.setName("Lucky"); UserDao userDao = (UserDao)ctx.getBean("userDao"); userDao.save(user); } }