上一阶段将struts映射完成,这一阶段目标是实现hibernate对blog数据库的封装,并将数据传回前端页面。
首先建立数据库,创建article表
CREATE TABLE `article` (
`a_id` int(11) NOT NULL AUTO_INCREMENT ,
`a_title` varchar(70) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`a_body` longtext CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`a_created_time` datetime NOT NULL ,
`a_last_modified_time` datetime NOT NULL ,
`a_status` varchar(1) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'p' ,
`a_abstract` varchar(54) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '1' ,
`a_views` int(10) UNSIGNED NOT NULL DEFAULT 1 ,
`a_likes` int(10) UNSIGNED NOT NULL DEFAULT 1 ,
`a_topped` tinyint(1) NOT NULL DEFAULT 1 ,
`a_category_id` int(11) NULL DEFAULT NULL ,
PRIMARY KEY (`a_id`),
)
在web工程目录下建立bean包,创建ArticleBean.java,对应article表建立属性以及getter、setter方法。
package bean;
import java.util.Date;
public class Article {
private Integer a_id;
private String a_title;
private String a_body;
private Date a_create_time;
private Date a_last_modified_time;
private String a_status;
private Integer a_abstract;
private Integer a_views;
private Integer a_likes;
private Integer a_topped;
private Integer a_category_id;
public Integer getA_id() {
return a_id;
}
public void setA_id(Integer a_id) {
this.a_id = a_id;
}
public String getA_title() {
return a_title;
}
public void setA_title(String a_title) {
this.a_title = a_title;
}
public String getA_body() {
return a_body;
}
public void setA_body(String a_body) {
this.a_body = a_body;
}
public Date getA_create_time() {
return a_create_time;
}
public void setA_create_time(Date a_create_time) {
this.a_create_time = a_create_time;
}
public Date getA_last_modified_time() {
return a_last_modified_time;
}
public void setA_last_modified_time(Date a_last_modified_time) {
this.a_last_modified_time = a_last_modified_time;
}
public String getA_status() {
return a_status;
}
public void setA_status(String a_status) {
this.a_status = a_status;
}
public Integer getA_abstract() {
return a_abstract;
}
public void setA_abstract(Integer a_abstract) {
this.a_abstract = a_abstract;
}
public Integer getA_views() {
return a_views;
}
public void setA_views(Integer a_views) {
this.a_views = a_views;
}
public Integer getA_likes() {
return a_likes;
}
public void setA_likes(Integer a_likes) {
this.a_likes = a_likes;
}
public Integer getA_topped() {
return a_topped;
}
public void setA_topped(Integer a_topped) {
this.a_topped = a_topped;
}
public Integer getA_category_id() {
return a_category_id;
}
public void setA_category_id(Integer a_category_id) {
this.a_category_id = a_category_id;
}
}
ArticleBean.java对应的ArticleBean.hbm.xml配置文件如下
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-2-25 15:16:51 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="bean.Article" table="ARTICLE">
<id name="a_id" type="java.lang.Integer">
<column name="A_ID" />
<generator class="native" />
</id>
<property name="a_title" type="java.lang.String">
<column name="A_TITLE"/>
</property>
<property name="a_body" type="java.lang.String">
<column name="A_BODY" length="16777216"/>
</property>
<property name="a_create_time" type="java.util.Date">
<column name="A_CREATE_TIME" />
</property>
<property name="a_last_modified_time" type="java.util.Date">
<column name="A_LAST_MODIFIED_TIME" />
</property>
<property name="a_status" type="java.lang.String">
<column name="A_STATUS" />
</property>
<property name="a_abstract" type="java.lang.Integer">
<column name="A_ABSTRACT" not-null="false"/>
</property>
<property name="a_views" type="java.lang.Integer">
<column name="A_VIEWS" />
</property>
<property name="a_likes" type="java.lang.Integer">
<column name="A_LIKES" />
</property>
<property name="a_topped" type="java.lang.Integer">
<column name="A_TOPPED" />
</property>
<property name="a_category_id" type="java.lang.Integer">
<column name="A_CATEGORY_ID" not-null="false"/>
</property>
</class>
</hibernate-mapping>
web工程的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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/blog</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="bean/Article.hbm.xml"/>
</session-factory>
</hibernate-configuration>
其中show_sql是显示sql语句;format_sql是格式化输出sql语句,输出的sql语句就不会是一行,便于查看;hbm2ddl.auto有几个参数:
create:表示启动的时候先drop,再create
create-drop: 也表示创建,只不过再系统关闭前执行一下drop
update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新
validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新
接下来封装一个HibernateSessionFacory,这样做的好处是便于控制session,将操作代码统一封装,减少重复代码
package myUtil;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try{
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
}catch(Exception e){
System.err.println("%%% Error Creating SessionFactory %%%");
e.printStackTrace();
}
}
private HibernateSessionFactory(){
}
//@return Session
//@throws HibernateExcception
public static Session getSession() throws HibernateException{
Session session = (Session) threadLocal.get();
if(session == null || session.isOpen()){
if(sessionFactory == null){
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession():null;
threadLocal.set(session);
}
return session;
}
private static void rebuildSessionFactory() {
try{
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
}catch(Exception e){
System.err.println("%%% Error Creating SessionFactory %%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException{
Session session = (Session)threadLocal.get();
threadLocal.set(null);
if(session != null){
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory(){
return sessionFactory;
}
public static void setConfigFile(String configFile){
HibernateSessionFactory.setConfigFile(configFile);
sessionFactory = null;
}
public static Configuration getConfiguration(){
return configuration;
}
//提供一个统一的查询方法(带分页) hql形式 from 类 where 条件=?
public static List excuteQueryByPage(String hql, String [] parameters, int pageSize, int pageNow){
Session session = null;
List list = null;
try {
session = getSession();
Query query = session.createQuery(hql);
if(parameters != null && parameters.length > 0){
for (int i=0; i<parameters.length; i++){
query.setString(i, parameters[i]);
}
}
query.setFirstResult((pageNow - 1) * pageSize).setMaxResults(pageSize);
list = query.list();
}catch(Exception e){
e.printStackTrace();
}finally{
}
return list;
}
//提供一个统一的查询方法hql 形式 from 类 where 条件=?
public static List excuteQuery(String hql, String [] parameters){
Session s = null;
List list = null;
try{
s = getSession();
Query query = s.createQuery(hql);
//判断是否有参数要绑定
if (parameters != null && parameters.length > 0){
for (int i=0; i<parameters.length; i++){
query.setString(i, parameters[i]);
}
}
list = query.list();
} catch(Exception e){
}finally {
closeSession();
}
return list;
}
}
编写ArticleService,用于操作数据库的artile表
package service;
import java.util.Iterator;
import java.util.List;
import org.hibernate.*;
import bean.Article;
import myUtil.HibernateSessionFactory;
public class ArticleService {
public ArticleService(){
}
public List<Article> getArtileByPage(int pageNow, int pageSize){
Session session = null;
Transaction tx = null;
List<Article> list = null;
try{
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
String hql = "from Article";
list = session.createQuery(hql).setFirstResult((pageNow - 1) * pageSize).setMaxResults(pageSize).list();
tx.commit();
}catch(Exception e){
e.printStackTrace();
if(tx != null){
tx.rollback();
}
}finally{
HibernateSessionFactory.closeSession();
}
return list;
}
public List<Article> getArtile(){
Session session = null;
Transaction tx = null;
List<Article> list = null;
try{
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
String hql = "from Article";
list = session.createQuery(hql).list();
tx.commit();
}catch(Exception e){
e.printStackTrace();
if(tx != null){
tx.rollback();
}
}finally{
HibernateSessionFactory.closeSession();
}
return list;
}
}
编写blogAction,用于响应客户端对article的请求,查询article,并以json形式返回
package action;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
import bean.Article;
import service.ArticleService;
public class blogAction extends ActionSupport {
private Map<Integer,Object> blogList;
public Map<Integer, Object> getBlogList() {
return blogList;
}
public String getArticle(){
System.out.println("getArticle");
ArticleService as = new ArticleService();
List<Article> list = as.getArtileByPage(2, 3);
blogList = new HashMap<Integer,Object>();
int i=1;
for (Article a:list){
blogList.put(i++, a);
}
System.out.print(blogList);
//blogList1 = as.getArtile();
//System.out.println(blogList);
return "blogList";
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
}
编写struts.xml,将对atricle的请求分派给blogAction
<action name="blogList" class="action.blogAction" method="getArticle">
<result name="blogList" type="json">
<param name="root">blogList</param>
</result>
</action>
前端js请求
$(document).ready(function(){
$.post({
url:'blogList',
data:'{}',
datatype:'json',
success:function(data){
console.log(data);
str = "";
$.each(data,function(i,e){
str += "<div class='blog-post'>";
str += "<h2 class='blog-post-title'>"+e['a_title']+"</h2>";
str += "<p class='blog-post-date'>"+e['a_last_modified_time']+"</p>";
str += "<p class='blog-post-abs'>"+e['a_body']+"</p>";
str += "</div>";
});
$("#blog").append(str);
}
})
});
效果如图
工程目录结构如下
网友评论