CRUD操作
1、使用hibernate把数据库模型和java对象进行ORM映射,通过配置文件或者注解完成。
2、程序通过hibernate提供的API进行CRUD,
C操作对应hibernate方法为save();(添加)
R操作对应hibernate方法为get();(查询)
U操作对应hibernate方法为update();(修改)
D操作对应hibernate方法为delete()。(删除)
User实体类、映射文件和hibernate配置文件请小伙伴们自己添加哦,这里忽略。
package com.connection;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static SessionFactory factory;
//static只初始化一次.
static
{
try{
//默认读取的是hibernate.cfg.xml 文件.
Configuration cfg = new Configuration().configure();
//建立SessionFactory.
factory = cfg.buildSessionFactory();
}catch(Exception e )
{
e.printStackTrace();
}
}
public static Session getSession()
{
//打开session.
return factory.openSession();
}
//关闭session.
public static void closeSession(Session session)
{
//判断是否为空.
//判断是否是打开状态再进行关闭.
if(session!=null)
{
if(session.isOpen())
{
session.close();
}
}
}
//返回工厂类.
public static SessionFactory getSessionFactory()
{
return factory;
}
}
CRUD的功能定义在此文件,在Action中调用相应方法。
学习的理解都写在了注解中。
package com.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import com.bean.User;
import com.connection.HibernateUtils;
public class UserDao {
List<User> users=new ArrayList<User>();
List<User> useres=new ArrayList<User>();
//查询并返回一个用户
public List<User> getOneUsers(int id) {
Session session=HibernateUtils.getSession();//获取session对象
User u=session.get(User.class, id);//id自动转换为Integer类型
if(u!=null) {
users.add(u);
System.out.println("查询用户成功");
System.out.println("用户名:"+u.getUsername()+",密码:
"+u.getUserpass()+",生日:"+u.getBirthday());
}
else
System.out.println("没有这个用户id");
HibernateUtils.closeSession(session);//关闭session
return users;
}
//查询并返回多个用户
public List<User> getMultipleUsers(String username) {
Session session=HibernateUtils.getSession();//获取session对象
users=session.createQuery("from User").list();
for(int i=0;i<users.size();i++) {
User user = users.get(i);
if(username.equals(user.getUsername())){
useres.add(user);
System.out.println("ID:"+user.getId()+" 用户名:"+user.getUsername());
}
}
if(useres.size()!=0)
System.out.println("查询用户成功");
else
System.out.println("没有这个用户名");
HibernateUtils.closeSession(session);//关闭session
return useres;
}
//查询并返回所有用户
public List<User> getAllUsers(){
Session session=HibernateUtils.getSession();//获取session对象
users=session.createQuery("from User").list();//hql
//获取集合里所有User对象数据存储到list中
System.out.println("查询所有用户成功");
//通过循环迭代userList集合 列出user对象
for(int i=0;i<users.size();i++) {
User u = users.get(i);
System.out.println("用户名:"+u.getUsername()+",
密码:"+u.getUserpass()+",生日:"+u.getBirthday());
}
HibernateUtils.closeSession(session);//关闭session
return users;
}
//查询是否存在该用户名(注册检查)
public int queryregister(String username) {
int flag=1;//不存在
Session session=HibernateUtils.getSession();//获取session对象
users=session.createQuery("from User").list();
for(int i=0;i<users.size();i++) {
User user = users.get(i);
if(username.equals(user.getUsername())){
flag=0;
System.out.println("ID:"+user.getId()+" 用户名:"+user.getUsername());
break;
}
}
HibernateUtils.closeSession(session);//关闭session
return flag;
}
//查询是否存在该用户名如果存在再判断密码是否匹配(登录)
public void querylogin(String username,String userpass) {
if(queryregister(username)==0) {
Session session=HibernateUtils.getSession();//获取session对象
users=session.createQuery("from User").list();
for(int i=0;i<users.size();i++) {
User user = users.get(i);
if(username.equals(user.getUsername())){
if(userpass.equals(user.getUserpass())){
System.out.println("ID:"+user.getId()+"
用户名:"+user.getUsername()+" 密码:"+user.getUserpass());
System.out.println("登录成功");
}
else
System.out.println("密码不正确");
break;
}
}
HibernateUtils.closeSession(session);//关闭session
}
else
System.out.println("没有这个用户名");
}
//添加用户
public void add(User u){
if(queryregister(u.getUsername())==1) {
Session session=HibernateUtils.getSession();//获取session对象
session.beginTransaction();//开启事务
//session.persist(u);//写入到数据库
session.save(u);//保存到数据库
session.getTransaction().commit();//提交事务
System.out.println("添加用户成功");
HibernateUtils.closeSession(session);//关闭session
}
else
System.out.println("数据库已存在该用户名,请重新添加");
}
//修改用户
public void updateone(User newuser,int id) {
if(queryregister(newuser.getUsername())==1) {
Session session=HibernateUtils.getSession();//获取session对象
session.beginTransaction();//开启事务
User u=session.get(User.class, id);
if(u!=null) {
u.setUsername(newuser.getUsername());
u.setUserpass(newuser.getUserpass());
u.setBirthday(newuser.getBirthday());
session.update(u);//修改数据
session.getTransaction().commit();//提交事务
System.out.println("修改用户成功");
System.out.println("用户名:"+u.getUsername()+",密码:
"+u.getUserpass()+",生日:"+u.getBirthday());
}
else
System.out.println("没有这个用户id");
HibernateUtils.closeSession(session);//关闭session
}
else
System.out.println("数据库已存在该用户名,请重新修改");
}
public void update(User newuser,int id) {
Session session=HibernateUtils.getSession();//获取session对象
session.beginTransaction();//开启事务
User u=session.get(User.class, id);
if(u!=null) {
if(queryregister(newuser.getUsername())==1||
newuser.getUsername().equals(u.getUsername()))
{
u.setUsername(newuser.getUsername());
u.setUserpass(newuser.getUserpass());
u.setBirthday(newuser.getBirthday());
session.update(u);//修改数据
session.getTransaction().commit();//提交事务
System.out.println("修改用户成功");
System.out.println("用户名:"+u.getUsername()+",密码:
"+u.getUserpass()+",生日:"+u.getBirthday());
}
else
System.out.println("数据库已存在该用户名,请重新修改");
HibernateUtils.closeSession(session);//关闭session
}
else
System.out.println("没有这个用户id");
}
//删除用户
public void delete(int id) {
Session session=HibernateUtils.getSession();//获取session对象
session.beginTransaction();//开启事务
User u=session.get(User.class, id);
if(u!=null) {
session.delete(u);//删除数据
session.getTransaction().commit();//提交事务
System.out.println("删除用户成功");
}
else
System.out.println("没有这个用户id");
HibernateUtils.closeSession(session);//关闭session
}
}
从Dao调用方法使用,这要配合struts.xml和相应jsp页面一起看。
package com.action;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.bean.User;
import com.dao.UserDao;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class JDBCAction extends ActionSupport{
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
List<User> users=new ArrayList<User>();//存储User对象的list
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
UserDao userDao=new UserDao();
public String aone() {
users=this.userDao.get OneUsers(user.getId());
if(users.size()==0)
request.setAttribute("tip","不存在该用户id");
return "list";
}
public String multiple() {
users=this.userDao.getMultipleUsers(user.getUsername());
if(users.size()==0)
request.setAttribute("tip","不存在该用户名");
return "list";
}
public String list() {
users=this.userDao.getAllUsers();
if(users.size()==0)
request.setAttribute("tip","还没有用户哟");
return "list";
}
public String add(){
this.userDao.add(this.user);
return "success";
}
public String update() {
this.userDao.update(user,user.getId());
return "success";
}
public String delete() {
this.userDao.delete(user.getId());
return "success";
}
public String edit(){
return "edit";
}
public void validateAone() {
if (user.getId()==null) {
this.addFieldError("user.id","请输入搜索内容");
}
}
public void validateMultiple() {
if (user.getUsername()==null||"".equals(user.getUsername().trim())) {
this.addFieldError("user.username","请输入搜索内容");
}
}
}
这里我使用通配符的形式,根据从jsp传来的数据调用相应的方法。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 配置Struts可以受理请求的扩展名value -->
<constant name="struts.action.extension" value="action,do,"></constant>
<!-- 打开允许动态方法条用的开关,默认是false -->
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
<package name="text" extends="struts-default">
<default-interceptor-ref name="paramsPrepareParamsStack"></default-interceptor-ref>
<action name="user_*" class="com.action.JDBCAction" method="{1}">
<result name="list">/user_list.jsp</result>
<result name="input">/user_list.jsp</result>
<result name="{1}">/user_{1}.jsp</result>
<result name="success" type="redirectAction">user_list</result>
</action>
</package>
</struts>
(1)一个简单的直接跳转到管理用户界面的按钮(index.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="user_list">list</a>
</body>
</html>
(2)注册界面(user_add.jsp)
<%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><s:text name="registerTitle"/></title>
<style>
table{
background-size:100% 100%;
border:2px solid gray;
margin:10% auto 0% auto;
}
td{
border:1px solid gray;
text-align:center;
}
</style>
</head>
<body>
<s:form action="user_add">
<s:textfield name="user.username" key="用户名"/>
<s:password name="user.userpass" key="密码"/>
<s:textfield name="user.birthday" key="出生年月日"/>
<s:submit name="submit" key="register"/>
</s:form>
</body>
</html>
(3)实现ID查询、用户名查询、用户修改和删除的界面(user_list.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
table{
background-size:100% 100%;
border:2px solid gray;
margin:1% auto 0% auto;
}
th,td{
background-color: #EBEBEB;
border:1px solid gray;
text-align:center;
}
</style>
</head>
<body>
<s:debug></s:debug>
<font color="red" size="5">${tip}</font><br>
<s:form action="user_aone">
<s:textfield name="user.id" label="id"/>
<s:submit/>
</s:form>
<s:form action="user_multiple">
<s:textfield name="user.username" label="username"/>
<s:submit/>
</s:form>
<table>
<tr>
<td colspan="6"><a href="user_list">管理所有用户</a></td>
</tr>
<tr>
<td colspan="6">查询结果</td>
</tr>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>生日</th>
<th colspan="2">操作</th>
</tr>
<!--users是action类中获取数据访问层中的方法返回的结果-->
<s:iterator value="users" var="u">
<tr>
<td>${u.id}</td>
<td><s:property value="username"/></td>
<td>${userpass}</td>
<td>${u.birthday}</td>
<td><a href="user_edit?user.id=${u.id}">修改</a></td>
<td><a href="user_delete?user.id=${u.id}">删除</a></td>
</tr>
</s:iterator>
<tr>
<td colspan="6"><a href="user_add.jsp">添加</a></td>
</tr>
</table>
</body>
</html>
(4)修改信息的界面(user_edit.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
table{
background-size:100% 100%;
border:2px solid gray;
margin:10% auto 0% auto;
}
td{
border:1px solid gray;
text-align:center;
}
</style>
</head>
<body>
<s:form action="user_update">
<s:hidden name="user.id"></s:hidden>
<s:textfield name="user.username" key="用户名"/>
<s:password name="user.userpass" key="密码"/>
<s:textfield name="user.birthday" key="出生年月日"/>
<s:submit name="submit" key="提交"/>
</s:form>
</body>
</html>
我的ID为什么不从1开始呢?因为我在前面测试的时候进行过添加删除等操作,数据库后台的ID自增了,想从1重新开始的话要重启数据库。
感谢你看到这里,希望对你有一丢丢的帮助!