最近准备换工作,所以复习了下hibernate,因为面试的时候问hbm配置问的比较多,所以没有采用注解,此小demo是加深hibernate配置的,采用的是ajax+struts2+hibernate3实现的一个批量查询小demo,用于加深理解hibernate基础。
一、引入相关jar。
二、配置web.xml,引用struts2.0。
<?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">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<display-name></display-name>
<welcome-file-list>
<welcome-file>author.html</welcome-file>
</welcome-file-list>
</web-app>
三、配置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>
<!--1 首先配置管理连接池对象 SessionFactory-->
<session-factory>
<!--2 配置JDBC基本连接参数-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myssh</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- 3 必须配置hibernate中数据库 方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 4 由Hibernate生成SQL语句,在控制台输出hibernate生成SQL -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property> <!-- 将语句格式化为多行 -->
<!-- 5 自动建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.connection.autocommit">true</property>
<!-- 加载配置文件 -->
<mapping resource="xk/entity/Author.hbm.xml" />
<mapping resource="xk/entity/Article.hbm.xml" />
</session-factory>
</hibernate-configuration>
四、配置log4j.properties。
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
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 mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=d\:mylog.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=info, stdout , file
五、新建HibernateUtils.java。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package xk.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
*
* @author john
*/
public class HibernateUtils {
private static Configuration configuration;
private static SessionFactory sessionFactory;
static{
configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
}
public static Session openSession(){
return sessionFactory.openSession();
}
public static void main(String[] args) {
Session session = openSession();
session.close();
}
}
六、新建两个实体类,作者和文章,是一对多的关系,并新建相对应的hbm。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package xk.entity;
/**
*
* @author john
*/
public class Article {
private Integer id;
private String title;
private String content;
private Author author;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
<?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>
<class name="xk.entity.Article" table="article">
<id name="id">
<generator class="native"></generator>
</id>
<property name="title"></property>
<property name="content"></property>
<!-- 多对一 -->
<many-to-one name="author" column="author_id" class="xk.entity.Author"></many-to-one>
</class>
</hibernate-mapping>
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package xk.entity;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author john
*/
public class Author {
private Integer id;
private String name;
Set<Article> articles = new HashSet<Article>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Article> getArticles() {
return articles;
}
public void setArticles(Set<Article> articles) {
this.articles = articles;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name + '}';
}
}
<?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>
<class name="xk.entity.Author" table="author">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<!-- 一对多 -->
<set name="articles" cascade="all-delete-orphan">
<key column="author_id"></key>
<one-to-many class="xk.entity.Article"></one-to-many>
</set>
</class>
</hibernate-mapping>
七、新建AuthorDao.java操作数据层。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package xk.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import xk.entity.Author;
import xk.utils.HibernateUtils;
/**
*
* @author john
*/
public class AuthorDao {
//查询所有的作者信息
public List<Author> findAllAuthor(){
Session session = HibernateUtils.openSession();
Transaction tx = session.beginTransaction();
List<Author> authors = session.createQuery("from Author").list();
tx.commit();
session.close();
return authors;
}
}
八、新建AuthorAction.java。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package xk.action;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import xk.dao.AuthorDao;
import xk.entity.Author;
import com.opensymphony.xwork2.ActionSupport;
/**
*
* @author john
*/
public class AuthorAction extends ActionSupport {
@Override
public String execute() throws Exception {
//查询所有作者信息
AuthorDao authorDAO = new AuthorDao();
List<Author> authors = authorDAO.findAllAuthor();
//通过json-lib 将信息序列化 字符串
// 不想Author中articles 集合被序列化
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{"articles"});
JSONArray jsonArray = JSONArray.fromObject(authors, jsonConfig);// 要序列化集合
String resultString = jsonArray.toString();
//使用response 写回客户端
ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
ServletActionContext.getResponse().getWriter().print(resultString);
return NONE;
}
}
九、配置strtus.xml。
<?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>
<constant name="struts.devMode" value="false" />
<package name="default" namespace="/" extends="struts-default">
<action name="showAuthors" class="xk.action.AuthorAction"></action>
</package>
</struts>
十、新建author.html。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function() {
$("#showAuthorButton").click(function() {
// 发起Ajax请求,去服务器端,获得所有作者的信息
$.get("showAuthors.action", function(data) {
// 将name 作为select 选择内容,将id 作为选项的value
for (var i = 0; i < data.length; i++) {
var id = data[i].id;
var name = data[i].name;
$("#authorselect").append($("<option value='" + id + "'>" + name + "</option>"));
}
});
});
});
</script>
</head>
<body>
<input type="button" value="点击我就可以知道时下最流行的作者" id="showAuthorButton"/>
<select name="author" id="authorselect">
<option value="">请选择作者</option>
</select>
</body>
</html>
完!