此次任务是简单的一次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' οnmοuseοver='overFn(this)' οnmοuseοut='outFn(this)' οnclick='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>
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请求进行站内搜索功能了!