User.class
@Entity
public class User {
private int id;
private String name;
@Id
@GeneratedValue
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;
}
public User(String name) {
super();
this.name = name;
}
}
StudentDao.class
@Repository("student")
public class StudentDao {
private SessionFactory factory;
public SessionFactory getFactory() {
return factory;
}
@Resource
public void setFactory(SessionFactory factory) {
this.factory = factory;
}
public void save(User user){
System.out.println("begin save!!!");
Session session=factory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
System.out.println("save success!!");
}
}
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<context:component-scan base-package="com.sl"/>
<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:3306/spring" />
<property name="username" value="root" />
<property name="password" value="qi" />
</bean>
<bean id="factory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="mydataSource"/>
<property name="annotatedClasses">
<list>
<value>com.sl.entity.User</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=create
</value>
</property>
</bean>
</beans>
test
public class test {
@Test
public void testOne(){
ApplicationContext appl=new ClassPathXmlApplicationContext("beans.xml");
StudentDao dao=(StudentDao)appl.getBean("student");
User user=new User("qing");
dao.save(user);
}
}