使用Spring+Spring MVC+Hibernate做增删改查开发效率真的很高。使用Hibernate简化了JDBC连接数据库的的重复性代码。下面根据自己做的一个简单的增加和查询,把一些难点分析出来:
首先项目目录结构:(Hibernate持久化数据连接信息交给Spring进行管理;别忘了加入Hibernate和Spring相关的架包.jar)
第一步:弄个用户实体类(配置Users.hbm.xml映射文件):
package com.ssh.SpringMVC.enity; public class Users { private int id;//id
private String username;//用户名
private String password;//密码
private String sex;//性别
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the sex
*/
public String getSex() {
return sex;
}
/**
* @param sex the sex to set
*/
public void setSex(String sex) {
this.sex = sex;
} }
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping
package="com.ssh.SpringMVC.enity"> <class name="Users" table="t_users">
<id name="id">
<generator class="increment"/>
</id>
<property name="username" />
<property name="password"/>
<property name="sex"/>
</class> </hibernate-mapping>
第二步:建个Dao层(公共类)
package com.ssh.SpringMVC.Dao; import java.util.List; /*
* 公共类
*/
public interface IBaseDao<T> {
//保存对象
public void save(T t);
//删除对象
public void delete(int id);
//更新对象
public void update(T t);
//根据id查询对象
public T getObjectByid(int id);
//查询所有对象
public List<T> getObjectALL();
//根据一组id查询一组对象
public List<T> getObjectByids(int ids); }
package com.ssh.SpringMVC.Dao.Impl; import java.lang.reflect.ParameterizedType;
import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; import com.ssh.SpringMVC.Dao.IBaseDao; /*
* 公共方法实现类
*/
@SuppressWarnings("unchecked")
@Transactional
public class IBaseDaoImpl<T> implements IBaseDao<T>{ //注入sessionfactory
@Resource
SessionFactory sessionFactory;
Class clazz; //构造方法:获取T的真实类型
public IBaseDaoImpl(){
ParameterizedType pType=(ParameterizedType) this.getClass().getGenericSuperclass();
clazz=(Class) pType.getActualTypeArguments()[0];
System.out.print(clazz.getSimpleName()); }
/*
* 删除对象
* (non-Javadoc)
* @see com.ssh.SpringMVC.Dao.IBaseDao#delete(int)
*/
public void delete(int id) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().delete(
sessionFactory.getCurrentSession().get(clazz, id));
} /*
* 查询所有对象
* (non-Javadoc)
* @see com.ssh.SpringMVC.Dao.IBaseDao#getObjectALL()
*/ public List<T> getObjectALL() {
// System.out.println("=====:"+"from"+clazz.getSimpleName());
// System.out.println("=====:"+"from "+clazz.getSimpleName());
// System.out.println("--------------"+clazz.getSimpleName());
return sessionFactory.getCurrentSession().createQuery("from "+clazz.getSimpleName()).list();
}
/*
* 根据id获取对象
* (non-Javadoc)
* @see com.ssh.SpringMVC.Dao.IBaseDao#getObjectByid(int)
*/
public T getObjectByid(int id) {
// TODO Auto-generated method stub
return (T) sessionFactory.getCurrentSession().get(clazz, id);
} /*
* 根据一组id获取一组对象
* (non-Javadoc)
* @see com.ssh.SpringMVC.Dao.IBaseDao#getObjectByids(int)
*/
public List<T> getObjectByids(int ids) {
// TODO Auto-generated method stub
return sessionFactory.getCurrentSession().createQuery(
"from"+clazz.getSimpleName()+"where id in(:ids)").setParameter("ids", ids).list();
}
/*
* 保存对象
* (non-Javadoc)
* @see com.ssh.SpringMVC.Dao.IBaseDao#save(java.lang.Object)
*/
public void save(T t) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().save(t);
} public void update(T t) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().update(t);
} }
第三步:Servse用户逻辑层
package com.ssh.SpringMVC.Servse; import com.ssh.SpringMVC.Dao.IBaseDao;
import com.ssh.SpringMVC.enity.Users; /*
* 用户逻辑层
*/ public interface IUserService extends IBaseDao<Users>{
//定义特有方法。。。
}
package com.ssh.SpringMVC.Servse.Impl; import org.springframework.stereotype.Service; import com.ssh.SpringMVC.Dao.Impl.IBaseDaoImpl;
import com.ssh.SpringMVC.Servse.IUserService;
import com.ssh.SpringMVC.enity.Users;
/*
* 用户实现类
*
*/
@Service("userService")
public class IUserServiceImpl extends IBaseDaoImpl<Users> implements IUserService{ }
第四步:配置applicationContext.xml和springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 引入外部配置文件 -->
<context:property-placeholder location="classpath:oracle.properties" /> <!-- 配置数据源(将所有的配置写在Spirng中) -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <!-- 数据库连接信息 -->
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="driverClassName" value="${driverClassName}" /> <!-- 最大连接数 -->
<property name="maxActive" value="${maxActive}" />
<!-- 最大空闲数 -->
<property name="maxIdle" value="${maxIdle}" />
<!--最小空闲数-->
<property name="minIdle" value="${minIdle}" />
<!-- 初始连接数 -->
<property name="initialSize" value="${initialSize}" /> </bean> <!-- 创建sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" /> <!-- 配置Hibernate配置信息 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
</property> <!-- 配置实体类映射信息 -->
<property name="mappingResources">
<list> <value>com/ssh/SpringMVC/enity/Users.hbm.xml</value> </list>
</property> </bean> <!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean> </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- SpringMVC的配置规则和Spring是一样的:无缝集成 -->
<!-- 配置扫描器;自动装配 -->
<context:component-scan base-package="com.ssh.SpringMVC" /> <!-- 注解事务配置 -->
<tx:annotation-driven transaction-manager="transactionManager" /> <!-- 配置视图 -->
<bean id="internalView"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置视图前缀 --> <property name="prefix" value="/" />
<!-- 配置视图后缀 -->
<property name="suffix" value=".jsp" />
</bean> </beans>
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- spring监听器: -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 指定spring文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <!-- =====================配置spring mvc Start================================= -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--配置springmvc路劲-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- >=0代表web容器启动的时候加载servlet(数字代表优先级) -->
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置编码过滤器 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
第五步:注册页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>用户注册</title> </head> <body>
<form action="userController?add" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="radio" name="sex" value="男" />男 <input type="radio" name="sex" value="女" />女</td>
</tr>
<tr>
<td></td>
<td><input type="submit" /></td>
</tr> </table> </form>
</body>
</html>
注册跳转至处理页:
package com.ssh.SpringMVC.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import com.ssh.SpringMVC.Servse.IUserService;
import com.ssh.SpringMVC.enity.Users; /**
* 控制层
* @author Administrator
*
*/
@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController { //注入业务层
@Resource
IUserService userService;
/*
* 添加用户
*/
@RequestMapping(params="add")
public String add(Users user){
userService.save(user); return "redirect:userController?all"; }
/*
* 查询所有对象
*/
@RequestMapping(params="all")
public ModelAndView all(){ //list集合
List<Users> li=userService.getObjectALL(); return new ModelAndView("index","userLi",li);
}
}
然后跳转至index.jsp查询所有用户信息:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>id</th>
<th>姓名</th>
<th>密码</th>
<th>性别</th>
</tr>
<c:forEach items="${userLi}" var="li">
<tr>
<td>${li.id}</td>
<td>${li.username}</td>
<td>${li.password}</td>
<td>${li.sex}</td>
</tr>
</c:forEach>
</table> </body>
</html>
陷阱先知:
本人在做查询的时候犯了个严重的不细心的问题:错误如下:
因为这个错纠结了一个多小时。原因是什么,看下图就明白了:
查询语句忘记了打空格,本来查询from Users,结果from Users合成一个fromUsers,才出现上面的错,都是不细心造成的,谨记,下次务犯。
您可以通过点击 右下角 的按钮 来对文章内容作出评价, 也可以通过左下方的 关注按钮 来关注我的博客的最新动态。 如果文章内容对您有帮助, 不要忘记点击右下角的 推荐按钮 来支持一下哦 如果您对文章内容有任何疑问, 可以通过评论或发邮件的方式联系我: 2276292708@qq.com或加入JAVA技术交流群:306431857 如果需要转载,请注明出处,谢谢!!