maven-struts2-hibernate 上一个随笔的基础上添加上hibernate支持
Posted lgp20151222
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了maven-struts2-hibernate 上一个随笔的基础上添加上hibernate支持相关的知识,希望对你有一定的参考价值。
配置文件
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>com.lgp</groupId> 5 <artifactId>maven_ssh</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>maven_ssh Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 <properties> 11 <project.build.sourceEncoding> 12 UTF-8 13 </project.build.sourceEncoding> 14 </properties> 15 <dependencies> 16 <dependency> 17 <groupId>junit</groupId> 18 <artifactId>junit</artifactId> 19 <version>3.8.1</version> 20 <scope>test</scope> 21 </dependency> 22 <!-- struts2的驱动包 --> 23 <dependency> 24 <groupId>org.apache.struts</groupId> 25 <artifactId>struts2-core</artifactId> 26 <version>2.3.31</version> 27 </dependency> 28 <!-- 添加Hibernate依赖 --> 29 <dependency> 30 <groupId>org.hibernate</groupId> 31 <artifactId>hibernate-core</artifactId> 32 <version>3.6.10.Final</version> 33 </dependency> 34 <dependency> 35 <groupId>log4j</groupId> 36 <artifactId>log4j</artifactId> 37 <version>1.2.16</version> 38 </dependency> 39 <dependency> 40 <groupId>org.slf4j</groupId> 41 <artifactId>slf4j-nop</artifactId> 42 <version>1.6.4</version> 43 </dependency> 44 <!-- mysql数据库的驱动包 --> 45 <dependency> 46 <groupId>mysql</groupId> 47 <artifactId>mysql-connector-java</artifactId> 48 <version>5.1.6</version> 49 </dependency> 50 </dependencies> 51 <build> 52 <finalName>maven_ssh</finalName> 53 </build> 54 </project>
熟悉的pom.xml其中lo4g和slf4j这两个包第一眼看上去有点莫名奇妙,我也是这么觉得的,实际作用是在后台输出sql语句,不导入hibernate就会报错。
web.xml和struts2一致即可
剩下的配置文件就放在resource文件夹以下即可
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file hibernate.log ### #log4j.appender.file=org.apache.log4j.FileAppender #log4j.appender.file.File=hibernate.log #log4j.appender.file.layout=org.apache.log4j.PatternLayout #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ### log4j.rootLogger=warn, stdout #log4j.logger.org.hibernate=info log4j.logger.org.hibernate=debug ### log HQL query parser activity #log4j.logger.org.hibernate.hql.ast.AST=debug ### log just the SQL #log4j.logger.org.hibernate.SQL=debug ### log JDBC bind parameters ### log4j.logger.org.hibernate.type=info #log4j.logger.org.hibernate.type=debug ### log schema export/update ### log4j.logger.org.hibernate.tool.hbm2ddl=debug ### log HQL parse trees #log4j.logger.org.hibernate.hql=debug ### log cache activity ### #log4j.logger.org.hibernate.cache=debug ### log transaction activity #log4j.logger.org.hibernate.transaction=debug ### log JDBC resource acquisition #log4j.logger.org.hibernate.jdbc=debug ### enable the following line if you want to track down connection ### ### leakages when using DriverManagerConnectionProvider ### #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
log4j.properties全是复制粘贴就好,硬要深究每一个的作用你可以一个一个的改,认真看都能看懂的。
<?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>创建与mysql的连接--> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">123456789</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">10</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.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <mapping resource="Table.hbm.xml" /> </session-factory> </hibernate-configuration>
hibernate.cfg.xml 注意<mapping resource="Table.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 package="com.entiy"> <class name="com.entity.User" table="USER"> <id name="id" column="ID"> <generator class="increment" /> </id> <property name="name" column="NAME" /> <property name="pwd" column="PWD" /> </class> </hibernate-mapping>
Table.hbm.xml一个</class>就是一个表格,所有表格都写在里面即可。hibernate在加载时,如果你没有表格,就会自行创建。
java代码
package com.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { // 定义静态的SessionFactory,产生单例,只生成一个SessionFactory private static final SessionFactory sessionFactory = buildSessionFactory(); // 用来初始化SessionFactory private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } // 得到SessionFactory public static SessionFactory getSessionFactory() { return sessionFactory;// 返回SessionFactory的对象 } }
HibernateUtil的工具类
package com.entity; public class User { private int id;// id private String name;// 名字 private String pwd;// 密码 public User() { } public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
user 就是表格的实体类,根据这个来创建表格
package com.action; import java.util.List; import java.util.Map; import org.apache.struts2.interceptor.RequestAware; import com.entity.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.util.ValueStack; import com.service.UserService; public class UserAction extends ActionSupport implements ModelDriven<User>, RequestAware { private static final long serialVersionUID = -1417237614181805435L; private User user; List<User> list; public List<User> getList() { return list; } public void setList(List<User> list) { this.list = list; } @SuppressWarnings("unused") private Map<String, Object> request; public String selectAll() { String sql = "from User"; UserService userService = new UserService();// model list = userService.findAll(sql); ValueStack vs = ActionContext.getContext().getValueStack(); vs.push(list); return "success"; } public String add() { UserService userService = new UserService();// model userService.add(user); return "success"; } public String delete() { UserService userService = new UserService();// model userService.delete(user); return "success"; } public String update() { UserService userService = new UserService();// model userService.update(user); return "success"; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public User getModel() { if (user == null) { user = new User(); } return user; } public void setRequest(Map<String, Object> arg0) { request = arg0; } }
action类
package com.dao; import java.util.List; import com.entity.User; public interface DBDao<T> { public List<T> selectAll(String sql); public int insert(User user); public void update(User user); public void delete(User user); }
dao接口
package com.dao.impl; import java.util.List; import org.hibernate.Session; import com.util.HibernateUtil; import com.dao.DBDao; import com.entity.User; public class DBDaoImpl<T> implements DBDao<T> { @SuppressWarnings("unchecked") public List<T> selectAll(String sql) { Session session = HibernateUtil.getSessionFactory().getCurrentSession();// 得到目前运行的session session.beginTransaction();// 开始事务 没有终结事务的方法 List<T> listUsers = session.createQuery(sql).list(); HibernateUtil.getSessionFactory().close(); return listUsers; } public int insert(User user) { Session session = HibernateUtil.getSessionFactory().getCurrentSession();// 得到目前运行的session session.beginTransaction();// 开始事务 没有终结事务的方法 int result = (Integer) session.save(user);// 保存对象 session.getTransaction().commit();// 提交事务 HibernateUtil.getSessionFactory().close(); return result; } public void delete(User user) { Session session = HibernateUtil.getSessionFactory().getCurrentSession();// 得到目前运行的session session.beginTransaction();// 开始事务 没有终结事务的方法 session.delete(user); session.getTransaction().commit();// 提交事务 HibernateUtil.getSessionFactory().close(); } public void update(User user) { Session session = HibernateUtil.getSessionFactory().getCurrentSession();// 得到目前运行的session session.beginTransaction();// 开始事务 没有终结事务的方法 session.update(user); session.getTransaction().commit();// 提交事务 HibernateUtil.getSessionFactory().close(); } }
DBDaoImpl接口的实现类,这里值得一提的是,有没有close,有没有beginTransaction,有没有commit,会有不会报错的逻辑bug,建议要么自己一个一个试试,要么像我这样贪方便(懒)全写。
package com.service; import java.util.List; import com.dao.impl.DBDaoImpl; import com.entity.User; public class UserService { @SuppressWarnings({ "unchecked", "rawtypes" }) public List<User> findAll(String sql) { DBDaoImpl Impl = new DBDaoImpl(); return Impl.selectAll(sql); } @SuppressWarnings("rawtypes") public int add(User user) { DBDaoImpl Impl = new DBDaoImpl(); return Impl.insert(user); } @SuppressWarnings("rawtypes") public void delete(User user) { DBDaoImpl Impl = new DBDaoImpl(); Impl.delete(user); } @SuppressWarnings("rawtypes") public void update(User user) { DBDaoImpl Impl = new DBDaoImpl(); Impl.update(user); } }
service类model控制事务
以上是关于maven-struts2-hibernate 上一个随笔的基础上添加上hibernate支持的主要内容,如果未能解决你的问题,请参考以下文章
Spring的annotation用在set方法上 hibernate的annotation用get方法上