我的beans.xml
- Java code
<?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" xmlns:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <context:annotation-config/> <aop:aspectj-autoproxy/> <context:component-scan base-package="com.impl"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- results in a setDriverClassName(String) call --> <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/> <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=clubdb"/> <property name="username" value="sa"/> <property name="password" value="123456"/></bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="annotatedClasses"> <list> <value>entity.User</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect <!-- SQLServerDialect --> </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> </beans>
我的UserImpl.java
- Java code
package com.impl;import java.sql.Connection;import java.sql.SQLException;import javax.annotation.Resource;import javax.sql.DataSource;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.junit.Test;import org.springframework.stereotype.Component;import com.entity.User;@Component("d3")public class UserImpl { 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.getCurrentSession(); s.beginTransaction(); s.save(user); s.beginTransaction().commit(); }}
我的user.java
- Java code
package com.entity;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class User {private int id;private String name;private String sex;@Id@GeneratedValuepublic 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 String getSex() { return sex;}public void setSex(String sex) { this.sex = sex;}}