SSH案例(一)

项目结构如下:

导包如下:

该项目中spring版本4.1.6,若采用4.3.8可能会造成jar包的冲突

web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>ssh</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 编码过滤器 解决中文编码问题 -->
  <filter>
    <display-name>CharacterEncodingFilter</display-name>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<description></description>
  		<param-name>encoding</param-name>
  		<param-value>utf-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- struts配置 -->
  <filter>
    <display-name>StrutsPrepareAndExecuteFilter</display-name>
    <filter-name>StrutsPrepareAndExecuteFilter</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>StrutsPrepareAndExecuteFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:conf/spring-*.xml</param-value>
  </context-param>
  
</web-app>

实体类User:

public class User implements Serializable{

	private static final long serialVersionUID = -8421782808743390486L;
	
	private String id;
	private String name;
	private String password;
	private String nick;
	private String token;
	public User() {}

User.hbm.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<!-- 将类映射到表: User类的对象存储到cn_user表中 -->
	<class name="cn.tedu.note.entity.User" table="cn_user">
		  <!-- id用于映射主键的对应关系 类中的id属性映射到表的cn_user_id列 -->
	      <id name="id" column="cn_user_id"></id>
	      
	      <!-- property 用于映射普通属性 -->
	      <property name="name" column="cn_user_name"></property>
	      <property name="password" column="cn_user_password"></property>
	      <property name="token" column="cn_user_token"></property>
	      <property name="nick" column="cn_user_nick"></property>
	</class>
</hibernate-mapping>

DAO接口UserDao:

package cn.tedu.note.dao;

import cn.tedu.note.entity.User;

public interface UserDao {
	public void addUser(User user);
	public void deleteUser(User user);
	public void updateUser(User user);
	public User findUserById(String id);
	public User findUserByName(String name);
}

DAO实现类:

package cn.tedu.note.dao;

import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import cn.tedu.note.entity.User;

@Repository("userDao")
@Transactional
public class UserDaoImpl implements UserDao{

	@Resource(name="hibernateTemplate")
	private HibernateTemplate hibernateTemplate;
	
	@Override
	public void addUser(User user) {
		hibernateTemplate.save(user);
	}

	@Override
	public void deleteUser(User user) {
		hibernateTemplate.delete(user);
	}

	@Override
	public void updateUser(User user) {
		hibernateTemplate.update(user);
	}

	@Override
	public User findUserById(String id) {
		return hibernateTemplate.get(User.class, id);
	}

	@Override
	public User findUserByName(String name) {
		//select * from cn_user where cn_user_name = ?
		//HQL
		//		   from User where name = ?
		String hql = "from User where name = ?";
		List<User> list = (List<User>) hibernateTemplate.find(hql, name);
		if(list.isEmpty()){
			return null;
		}
		return list.get(0);
	}

}

Service接口UserService:

package cn.tedu.note.service;

import cn.tedu.note.entity.User;

public interface UserService {
	public User login(String username, String password);
}

Service实现类UserServiceImpl:

package cn.tedu.note.service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import cn.tedu.note.dao.UserDao;
import cn.tedu.note.entity.User;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource(name="userDao")
	private UserDao userDao;
	
	@Override
	@Transactional
	public User login(String username, String password) {
		User user = userDao.findUserByName(username);
		if(user == null){
			//没有找到该用户
			throw new RuntimeException("用户名错误");
		}
		if(user.getPassword().equals(password)){
			return user;
		}
		throw new RuntimeException("密码错误");
	}

}

配置文件spring-orm.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:context="http://www.springframework.org/schema/context" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
	
	<util:properties id="config" location="classpath:conf/db.properties"/>
	<!-- 配置数据库连接池DBCP -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="#{config.driver}" />
		<property name="url" value="#{config.url}" />
		<property name="username" value="#{config.username}" />
		<property name="password" value="#{config.password}" />
		<property name="maxActive" value="#{config.maxactive}" />
	</bean>
	
	<!-- 配置Hibernate的SessionFactory 返回SessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
	<!-- 连接数据库 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 配置Hibernate的参数 方言 显示SQL等 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
		<!-- 映射文件列表 -->
		<property name="mappingLocations">
			<list>
				<value>classpath:hbm/User.hbm.xml</value>
			</list>
		</property>
	</bean>
	
	<!-- 配置Hibernate Template -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	<!-- 声明事务管理 -->
	<tx:annotation-driven transaction-manager="txManager"/>
	<!-- 配置事务管理器 -->
	<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	<!-- 组件扫描 -->
	<context:component-scan base-package="cn.tedu.note.dao"/>
</beans>

配置文件spring-service.xml:里面只有一句如下

<context:component-scan base-package="cn.tedu.note.service"/>

测试类:

package cn.tedu.test.dao;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBase {

	protected ClassPathXmlApplicationContext ctx;

	public TestBase() {
		super();
	}

	public void initCtx() {
		String[] cfg = {
				"conf/spring-orm.xml",
				"conf/spring-service.xml"
				};
		ctx = new ClassPathXmlApplicationContext(cfg);
	}

}

测试数据库连接:

package cn.tedu.test.dao;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;


public class TestCase extends TestBase{

	@Test
	//测试数据库连接
	public void testDataSource() throws SQLException{
		initCtx();
		DataSource ds = ctx.getBean("dataSource",DataSource.class);
		Connection conn = ds.getConnection();
		System.out.println(conn);
		conn.close();
	}
	
}

测试DAO层:

package cn.tedu.test.dao;

import org.junit.Before;
import org.junit.Test;

import cn.tedu.note.dao.UserDao;
import cn.tedu.note.entity.User;


public class UserDaoTestCase extends TestBase{

	private UserDao dao;
	
	@Before
	public void initDao(){
		initCtx();
		dao = ctx.getBean("userDao",UserDao.class);
	}
	
	@Test
	public void testAddUser(){
		User user = new User("2","Jerry","123","","");
		dao.addUser(user);
	}
	
	@Test
	public void testFindByName(){
		String name = "Lili";
		User user = dao.findUserByName(name);
		System.out.println(user);
	}
}

其中testFindByName使用的是HQL语句:

Hibernate为了消除SQL提供了替代的查询语言 HQL.

HQL的语法与SQL非常类似:

  1. 将SQL中的表名替换为对应的实体类名
  2. 将SQL中的列名(字段名)替换为对应的实体属性名
  3. 使用Query接口执行HQL查询

Service层测试:

package cn.tedu.test.service;

import org.junit.Before;
import org.junit.Test;

import cn.tedu.note.entity.User;
import cn.tedu.note.service.UserService;
import cn.tedu.test.dao.TestBase;

public class UserServiceTestCase extends TestBase{
	private UserService service;
	
	@Before
	public void init(){
		initCtx();
		service = ctx.getBean("userService",UserService.class);
	}
	
	@Test
	public void testLogin(){
		String username = "Lili";
		String password = "123";
		User user = service.login(username, password);
		System.out.println(user);
		
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值