配置hbm的hibernate小demo(入門級小案例ajax+struts2.0+hibernate3.0)

最近準備換工作,所以複習了下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>

完!



發佈了28 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章