继续上一篇,struts已经搭好了,接下来要往shDemo工程里面加入持久层框架Hibernate。
1.导入Hibernate所需要的包
把hibernate-release-5.2.1.Final\hibernate-release-5.2.1.Final\lib下required文件夹中的所有jar包导入工程,还有mysql-connector-java-5.1.39-bin.jar包,bulid path。
注:本次搭建不使用数据源,加入数据源会在下一篇整合spring时再加上。
2.创建对应数据库表的用户对象
com.tzy.bean.User.java
package com.tzy.bean;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
3.创建User.hbm.xml映射文件
com.tzy.dao.User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.tzy.bean">
<class name="User" table="user">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="username" column="username" type="java.lang.String"
not-null="true" length="20"></property>
<property name="password" column="password" type="java.lang.String"
not-null="true" length="20" />
</class>
</hibernate-mapping>
在src目录下创建Hibernate.cfg.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/tzy?characterEncoding=utf8&useSSL=true</property>
<property name="connection.username">tzy</property>
<property name="connection.password">********</property>
<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property> -->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<!-- <property name="current_session_context_class">thread</property> -->
<!-- Disable the second-level cache -->
<!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> -->
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">update</property> -->
<mapping resource="com/tzy/bean/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>5.实现LoginDao接口(数据访问对象)
com.tzy.daoImpl.LoginDaoImpl.java
package com.tzy.daoImpl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.tzy.bean.User;
import com.tzy.dao.LoginDao;
public class LoginDaoImpl implements LoginDao {
User user;
//hibernate读取对象所定义的对象
private static final String CFG_FILE_LOCATION = "/Hibernate.cfg.xml";
Configuration cfg;
StandardServiceRegistryBuilder serviceRegistry;
SessionFactory sessionFactory;
Session session;
Transaction ts;
@SuppressWarnings("unchecked")
@Override
public User getUser(String username) {
user = new User();
//用hibernate从数据库获取user
cfg = new Configuration().configure(CFG_FILE_LOCATION).addClass(com.tzy.bean.User.class);
//5.*以前用ServiceRegistryBuilder
//5.*以后用StandardServiceRegistryBuilder
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
sessionFactory = cfg.buildSessionFactory(serviceRegistry.build());
session = sessionFactory.openSession();
ts = session.beginTransaction();
//hql查询
String hql = "from User";
@SuppressWarnings({"rawtypes"})
List result = session.createQuery(hql).getResultList();
for(User user2 : (List<User>)result){
if(username.equals(user2.getUsername())){
user.setUsername(user2.getUsername());
user.setPassword(user2.getPassword());
}
}
//测试用
System.out.println("可以连接数据库");
ts.commit();
session.close();
if(user.getUsername()!=null){
return user;
}else{
return new User();
}
}
}
注:
1.这里的代码可以通过,但并不是最佳,理想状态是在session.createQuery(hql)这里最好用条件查询,只返回一个对象,但是我写的时候报错,这里不多纠结,就先用获取对象列表再逐一比对的笨方法代替,毕竟我的主要工作不是研究Hibernate的API,这里我试过生成一对象,用session.save(user)、session.delete(user)、session.update(user)方法操作数据库都成功。
2.搭建的时候遇到一点小麻烦,随着版本提升,有些API发生变化,最重要的有两点,一是new Configuration().configure(CFG_FILE_LOCATION).addClass(com.tzy.bean.User.class); 5.*以上版本这里一定要引入对象,在后面一定要加上.addClass(com.tzy.bean.User.class),不然调bug够你喝一壶的;二是ServiceRegistryBuilder被StandardServiceRegistryBuilder替代。
6.实现LoginService接口(业务逻辑对象)
package com.tzy.serviceImpl;
import com.tzy.bean.User;
import com.tzy.daoImpl.LoginDaoImpl;
import com.tzy.service.LoginService;
public class LoginServiceImpl implements LoginService {
LoginDaoImpl loginDao;
User user;
@Override
public String checkUser(String username, String password) {
loginDao = new LoginDaoImpl();
user = loginDao.getUser(username);
if(user.getUsername()!=null){
if(password.equals(user.getPassword())){
return "success";
}else{
return "error";
}
}else{
return "register";
}
}
}
这样Struts+Hibernate框架就搭建成功了,最终的代码结构如下:
运行项目,可以正确的操作数据库。
本文介绍如何在Eclipse环境中整合Struts2.3.29、Hibernate5.2.1,不使用数据源,详细步骤包括导入所需库,创建用户对象及映射文件,配置Hibernate.cfg.xml,实现业务逻辑,最终实现对数据库的正确操作。
2270

被折叠的 条评论
为什么被折叠?



