【SSH学习笔记】整合spring3-hibernate的小项目(一)

需求分析:

1、使用spring注入dataSourse数据源

2、使用BaseDao获取注入SessionFactory并返回Session

3、实现查询所有和按字符串查询的方法

4、使用JUNIT测试

【配套的资源代码已经上传,有兴趣的朋友可以下载看看点击打开链接


操作步骤:

1、创建用户表并添加测试数据

create table users(
  userid number(8) primary key,
  username nvarchar2(10),
  password nvarchar2(10),
  birthday date,
  flag number(8)
);
insert into users values(1,'zhangsan','123',to_date('1992-1-1','yyyy-MM-dd'),0);
insert into users values(2,'lisi','123',to_date('1992-1-1','yyyy-MM-dd'),0);

2、创建用户实体并写好注解

import java.util.Date;
@Entity
@Table(name="users")
public class User {
	
	private int userid;
	private String username;
	private String password;
	private Date birthday;
	private int flag;
	
	@Id
	@GeneratedValue
	public int getUserid() {
		return userid;
	}
	public void setUserid(int userid) {
		this.userid = userid;
	}
	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 Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public int getFlag() {
		return flag;
	}
	public void setFlag(int flag) {
		this.flag = flag;
	}
	public User() {
		super();
	}
	public User(int userid, String username, String password, Date birthday,
			int flag) {
		super();
		this.userid = userid;
		this.username = username;
		this.password = password;
		this.birthday = birthday;
		this.flag = flag;
	}

}

3、导入Spring3和hibernate3.0所需JAR包,创建applicationContext.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" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	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
						http://www.springframework.org/schema/aop 
						http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
						http://www.springframework.org/schema/tx 
						http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<context:component-scan base-package="com.wyd"/>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.OracleDriver">
		</property>
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:adminwyd">
		</property>
		<property name="username" value="scott"></property>
		<property name="password" value="tiger"></property>
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="packagesToScan">
			<value>com.wyd.entity</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.Oracle9Dialect
				</prop>
				<prop key="hibernate.hbm2ddl">update</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
	</bean>

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<aop:config>
		<aop:pointcut id="productServiceMethods" expression="execution(* com.wyd.dao.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods" />
	</aop:config>

	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>

</beans>

4、创建BaseDao、IUserDao接口及其实现类

public class BaseDao {

	@Resource
	private SessionFactory sessionFactory;
	
	protected Session getSession(){
		return this.sessionFactory.getCurrentSession();
	}
	
}

public interface IUserDao {
	
	public List<User> findAll();
	
	public User isUser(String username);

}

@Repository("userDao")
public class UserDao extends BaseDao implements IUserDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll() {
		List<User> list = this.getSession().createQuery("from User").list();
		return list;
		
	}

	@Override
	public User isUser(String username) {
		User user = (User) this.getSession().createQuery("from User where username='"+username+"'").uniqueResult();
		return user;
	}

}

5、创建UserTest测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext.xml")
public class UserTest {
	
	@Resource(name = "userDao")
	private IUserDao userDao;

	@Test
	public void findAll(){
		System.out.println(userDao.findAll().size());
	}
	
	@Test 
	public void isUser(){
		System.out.println(userDao.isUser("zhangsan").getBirthday());
	}

}



6、运行结果

测试findAll():
Hibernate:
    select
        user0_.userid as userid0_,
        user0_.birthday as birthday0_,
        user0_.flag as flag0_,
        user0_.password as password0_,
        user0_.username as username0_
    from
        users user0_
2

测试isUser():
Hibernate:
    select
        user0_.userid as userid0_,
        user0_.birthday as birthday0_,
        user0_.flag as flag0_,
        user0_.password as password0_,
        user0_.username as username0_
    from
        users user0_
    where
        user0_.username='zhangsan'
1992-01-01 00:00:00.0


用《开发者突击》里面的初步搭建SSH2的代码,连接sqlserver2005,出现下面提示: Hibernate: select user0_.ID as ID, user0_.username as username0_, user0_.password as password0_, user0_.email as email0_ from user user0_ where user0_.username=? WARN - SQL Error: 156, SQLState: S0001 ERROR - 关键字 &#39;user&#39; 附近有语法错误。 2010-12-28 22:22:11 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet default threw exception com.microsoft.sqlserver.jdbc.SQLServerException: 关键字 &#39;user&#39; 附近有语法错误。 数据库中我建了表 user,属性有id username password email。 applicationContext 代码如下: [code="xml"] <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"> </property> <property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=DeviceManagement;"> </property> <property name="username" value="sa"></property> <property name="password" value="123456"></property> </bean> <!-- 配置Hibernate --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="mappingResources"> <list> <value>com/demo/hibernate/beans/User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <!-- 配置事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref local="sessionFactory" /> </property> </bean> <!-- 定义DAO --> <bean id="userDAO" class="com.demo.hibernate.dao.UserDAO"> <property name="sessionFactory"> <ref local="sessionFactory" /> </property> </bean> <!-- 定义DAO代理 --> <bean id="UserDAOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager" /> </property> <property name="target"> <ref local="userDAO" /> </property> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> <!-- 定义Struts配置 --> <bean name="loginAction" class="com.demo.struts2.actions.LoginAction"> <property name="userDAO"> <ref local="userDAO" /> </property> </bean> <bean name="logoutAction" class="com.demo.struts2.actions.LogoutAction"> <property name="userDAO"> <ref local="userDAO" /> </property> </bean> <bean name="registerAction" class="com.demo.struts2.actions.RegisterAction"> <property name="userDAO"> <ref local="userDAO" /> </property> </bean> <!-- 配置拦截器 --> <bean name="logger" class="com.demo.spring.aop.LoggingInterceptor" /> <!-- 配置拦截器代理 --> <bean name="loggingAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <list> <value>/login</value> <value>/register</value> </list> </property> <property name="interceptorNames"> <list> <value>logger</value> </list> </property> </bean> [/code] [size=x-large]提示错误行在UserDao里面, [/size]UserDao [code="java"] package com.demo.hibernate.dao; import java.util.ArrayList; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.demo.hibernate.beans.User; public class UserDAO extends HibernateDaoSupport implements IUserDAO { // 验证用户名和密码 public boolean isValid(final String username, final String password) { System.out.println("UserDao检验是否有效"); System.err.println("username:"+username+",password:"+password); List list = (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { /////////////////////////////////////这里报错/////////////////////////////// List result = session.createCriteria(User.class).add( Restrictions.eq("username", username)).add( Restrictions.eq("password", password)).list(); return result; } }); if (list.size() > 0) { return true; } else { return false; } } // 判断某个用户是否存在,只需用用户名查询就可以 public boolean isExist(final String username) { System.err.println("UserDao进行查询"); List list = (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { List result = session.createCriteria(User.class).add( Restrictions.eq("username", username)).list(); return result; } }); if (list.size() > 0) { return true; } else { return false; } } //插入新的用户对象到数据库 public void insertUser(User user) { System.err.println("UserDao插入数据"); getHibernateTemplate().saveOrUpdate(user); } //从数据库中取得用户对象 public User getUser(String userid) { System.err.println("UserDao取得对象"); return (User) getHibernateTemplate().get(User.class, new Integer(userid)); } //取得用户所有详细信息 public List getUsers() { System.err.println("UserDao取得数据"); return getHibernateTemplate().find("from User"); } //删除某个用户的所有信息 public void deleteUser(String userid) { System.err.println("UserDao删除某个用户的所有信息"); Object p = getHibernateTemplate().load(User.class, new Integer(userid)); getHibernateTemplate().delete(p); } } [/code] 请问这是为什么呢?
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页