1. 程式人生 > >利用JQuery傳送ajax請求進行站內搜尋(Hibernate篇——超簡單系列)

利用JQuery傳送ajax請求進行站內搜尋(Hibernate篇——超簡單系列)

此次任務是簡單的一次hibernate框架小訓練,利用上一篇的專案修改

1.導包,找到Hibernate-release-5.x.x.Final\lib\required下的所有包,copy到專案WEB-INF\lib下



2.開始編寫資料庫表(名字好煩,就亂取了)

//建表hibernate

create table my_hibernate(
`h_id` integer not null auto_increatment,
`h_name` varchar (255) null,
primary key (`h_id`)
) ;

//建表table

 create table my_table(
 

`t_id` integer not null auto_increatment,
`t_name` varchar(255) null,
  primary key (`t_id`)
 );


3.建立實體類

MyTable類:(可以把上面my_table表語句複製過來,照著鍵名複製,以免出錯)

import java.util.Set;

public class MyTable {
//	 create table my_table(
//			 `t_id` integer not null,
//			 `t_name` varchar(255) null,
//			 primary key (`t_id`)
//			 );
	private Integer t_id;
	private String t_name;
	public Integer getT_id() {
		return t_id;
	}
	public void setT_id(Integer t_id) {
		this.t_id = t_id;
	}
	public String getT_name() {
		return t_name;
	}
	public void setT_name(String t_name) {
		this.t_name = t_name;
	}
	private Set<MyHibernate> myHibernate;
	public Set<MyHibernate> getMyHibernate() {
		return myHibernate;
	}
	public void setMyHibernate(Set<MyHibernate> myHibernate) {
		this.myHibernate = myHibernate;
	}
	
	
}

MyHibernate類:

import java.util.Set;

public class MyHibernate {
//	create table my_hibernate(
//			`h_id` integer not null auto increatment,
//			`h_name` varchar (255) null,
//			primary key (`h_id`)
//		) 
	
	private Integer h_id;
	private String h_name;
	
	public Integer getH_id() {
		return h_id;
	}
	public void setH_id(Integer h_id) {
		this.h_id = h_id;
	}
	public String getH_name() {
		return h_name;
	}
	public void setH_name(String h_name) {
		this.h_name = h_name;
	}
	private Set<MyTable> myTable;
	public Set<MyTable> getMyTable() {
		return myTable;
	}
	public void setMyTable(Set<MyTable> myTable) {
		this.myTable = myTable;
	} 
	
}


4.在當前包下建立xml檔案,編寫orm對映類

MyHibernate.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="xxx.xxx.domain">
    	<class name="MyHibernate" table="my_hibernate">
    		<id name="h_id">
    			<generator class="native"></generator>
    		</id>
    		<property name="h_name" column="h_name"></property>
    		<set name="myTable" table="table_hibernate" inverse="true">
    			<key column="h_id"></key>
    			<many-to-many class="MyTable" column="t_id"></many-to-many>
    		</set>
    	</class>
    
    </hibernate-mapping>

MyTable.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="xxx.xxx.domain">
    	<class name="MyTable" table="my_table">
    		<id name="t_id">
    			<generator class="native"></generator>
    		</id>
    		<property name="t_name"></property>
    		<set name="myHibernate" table="table_hibernate" inverse="false">
    			<key column="t_id"></key>
    			<many-to-many class="MyHibernate" column="h_id"></many-to-many>
    		</set>
    	</class>
    </hibernate-mapping>


5.編寫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.url">jdbc:mysql:///test</property>
			<property name="hibernate.connection.username">root</property>
			<property name="hibernate.connection.password">123</property>
			<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
			
			<property name="hibernate.show_sql">true</property>
			<property name="hibernate.format_sql">true</property>
			
			<property name="hibernate.hbm2ddl.auto">update</property>
			
			<property name="hibernate.connection.isolation">4</property>
			<property name="current_session_context_class">thread</property>
			
			<mapping resource="cn/zhku/jsjs/haofeng/domain/MyHibernate.hbm.xml"/>
			<mapping resource="cn/zhku/jsjs/haofeng/domain/MyTable.hbm.xml"/>
			
		
		</session-factory>
	</hibernate-configuration>

6.測試,建立test類,進行junit測試看看能否成功建表

package test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import cn.zhku.jsjs.haofeng.domain.MyTable;

public class ProjectTest {
	@Test
	public void test(){
		Configuration conf = new Configuration().configure();
		SessionFactory SessionFactory = conf.buildSessionFactory();
		Session session = SessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		MyTable t1 = session.get(MyTable.class, 01);
		t1.setT_name("you not 1");
		session.save(t1);
		transaction.commit();
		session.close();
		SessionFactory.close();
	}
}
塗紅兩句是獲取Mytable中id為01的記錄,然後設定t_name為"you not 1"(在測試前在my_table表中插入一條t_id為01的資料即可)

就能看到table_hibernate被成功創建出來了,說明多對對關係建立成功


my_table表資料也被修改成功



7.接著,只用把上一篇的程式碼進行小小調整即可(紅色部分即為調整地方

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
</head>
<script type="text/javascript" src="JS/jquery-1.11.0.js"></script>
<script type="text/javascript">
//為搜尋繫結聚焦事件
$(function(){
	$("#search").keyup(function(){
		var content = $(this).val();
		var returnStr = "";
		$.post(
			"/ajax_backstage3/ajaxServletHibernateTest",
			{"content":content},
			function(data){
				if(data.length>0){
					for(var i=0;i<data.length;i++){
						returnStr += "<div id='div' style='padding:5px;cursor:pointer' onmouseover='overFn(this)' onmouseout='outFn(this)' onclick='clickFn(this)'>"+data[i]+"</div>";//
					} 
					$("#div").html(returnStr);
					$("#div").css("display","block");
				}else{
					$("#div").css("display","none");
				}
			},
			"json"
		);	
	});
	$("#search").blur(function(){
		$("#div").css("display","none");
	});
})
//繫結按鈕事件
$(function(){
	$("#button").click(function(){
		var sub = $("#search").val();
		$.ajax({
			type:"POST",
			url:"/ajax_backstage3/ajaxServletHibernateTest",
			contentType:"application/json",
			data:JSON.stringify({"sub":sub}),
			dataType:"json",
			success:function(result){
				//請求正確後的操作
			},
			error:function(result){
				//請求失敗後的操作
			}
		});
	});
})
//對div新增滑鼠移入效果
function overFn(obj){
	$(obj).css("background-color","yellow");
}

//對div新增滑鼠移出效果
function outFn(obj){
	$(obj).css("background-color","#F0F8FF");
}

//對div內容新增點選效果
function clickFn(obj){
	$("#search").val($(obj).html());
	$("#div").css("display","none");
}


</script>
<body>	
	<input type="text" id="search" /><input type="button" id="button" value="按鈕">
	<div id="div" style="width:150px;display:none;background-color: #F0F8FF"></div>
	
</body>
</html>


Servlet:( 不用改,我修改了類名和方法名,綠色標誌

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import xxx.xxx.service.SearchHibernateService;

/**
 * Servlet implementation class ajaxServletHibernateTest
 */
public class ajaxServletHibernateTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ajaxServletHibernateTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//從前臺獲取json格式資料
				request.setCharacterEncoding("UTF-8");
				String content = (String) request.getParameter("content");
				//建立一個service類,並呼叫其查詢方法
				SearchHibernateService ss = new SearchHibernateService();
				List<String> list = null;
				list = ss.SearchHname(content);
				
				System.out.println(list);
				//將service返回的資料進行格式轉換變成json
				//先建立一個Gson
				Gson gson = new Gson();
				//然後解析獲得的list,把json轉換成string
				String str = gson.toJson(list);
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write(str);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Service:(紅色部分為新增的事務操作,綠色部分為修改類名或方法名)
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.zhku.jsjs.haofeng.dao.SearchHibernateDao;
import cn.zhku.jsjs.haofeng.utils.HibernateUtils;

public class SearchHibernateService {
	public List<String> SearchHname(String content){
		Session session = HibernateUtils.getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		SearchHibernateDao shd = new SearchHibernateDao();
		List<String> list = shd.searchHname(content);
		tx.commit();
		return list;
		
		
		
	}
}

Dao:( 這裡就是hibernate的sql查詢操作了
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;

import cn.zhku.jsjs.haofeng.utils.HibernateUtils;

public class SearchHibernateDao {
	public List<String> searchHname(String content){
		Session session = HibernateUtils.getCurrentSession();
		String sql = "select h_name from my_hibernate where h_name like '%"+content+"%'";
		SQLQuery query = session.createSQLQuery(sql);
		List<String> list = query.list();
		return list;
	}
}

HibernateUtils:(把hibernate的啟動,初始化,建立session操作的重複程式碼封裝,封裝了getOpenSession和getCurrentSession兩個方法)

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class HibernateUtils {
	private static SessionFactory sf;
	static{
		Configuration conf = new Configuration().configure();
		sf = conf.buildSessionFactory();
	}
	
	public static Session getOpenSession(){
		
		Session session = sf.openSession();
		return session;
	}
	public static Session getCurrentSession(){
		Session session = sf.getCurrentSession();
		return session;
	}
}

把相關資料庫服務是開啟的,資料庫使用者名稱密碼設定為自己的,往資料庫中的my_hibernate表中填幾個資料,就能實現上一篇的頁面傳送ajax請求進行站內搜尋功能了!