1. 程式人生 > >Hibernate-----多條件查詢,多對多新增查詢案例

Hibernate-----多條件查詢,多對多新增查詢案例

======================================================================================================

1.表單輸入條件

 <body>
   <form action="MovieServlet?opr=sselct" method="post">
   <table width="595" height="187" border="0">
  <tr>
    <td width="100">電影名稱:</td>
    <td width="300"><input type="text" name="name" />&nbsp;&nbsp;&nbsp;&nbsp;輸入關鍵字即可</td>
  </tr>
  <tr>
    <td>電影型別:</td>
    <td><select name="typeid">
    <option value=0>全選</option>
     <c:forEach items="${listType}" var="type" varStatus="status">
     
     <option value=${type.typeid}>${type.typename }</option>
     </c:forEach></select>
     
    
</td>
  </tr>
  <tr>
    <td>主演:</td>
    <td>&nbsp;<input type="text" name="actor" />&nbsp;&nbsp;&nbsp;&nbsp;輸入關鍵字即可</td>
  </tr>
  <tr>
    <td>導演:</td>
    <td>&nbsp;<input type="text" name="author" />&nbsp;&nbsp;&nbsp;&nbsp;輸入關鍵字即可</td>
  </tr>
  <tr>
    <td>價格:</td>
    <td><input name="smallprice" type="text"/>至<input name="bigprice" type="text"/></td>
  </tr>
</table>
<input type="submit" value="提交">
   </form>
  </body>

======================================================================================================

2.MovieServlet?opr=sselct

if("sselct".equals(opr)){
String name = request.getParameter("name").trim();
String actor = request.getParameter("actor").trim();
String author = request.getParameter("author").trim();
String smallprice = request.getParameter("smallprice").trim();
String bigprice = request.getParameter("bigprice").trim();
String typeid = request.getParameter("typeid").trim();



MovieCondition mc=new  MovieCondition();
if(typeid!="0"){
Integer i=Integer.parseInt(typeid);
Type t=tbi.findById(i);
mc.setTypeset(t);
}
if((name!=null)&&!"".equals(name)){
mc.setName(name);
}
if((actor!=null)&&!"".equals(actor)){
mc.setActor(actor);
}
if((author!=null)&&!"".equals(author)){
mc.setAuthor(author);
}
if((smallprice!=null)&&!"".equals(smallprice)){
mc.setSmallprice(Integer.parseInt(smallprice ));
}else{
mc.setSmallprice(0);
}
if((bigprice!=null)&&!"".equals(bigprice)){
mc.setBigprice(Integer.parseInt(bigprice ));
}else{
mc.setBigprice(new Integer(Integer.MAX_VALUE));
}
List<Movie> listMovie=mbi.check(mc);

request.getSession().setAttribute("listMovie", listMovie);
request.getRequestDispatcher("index.jsp?opt=chk").forward(request, response);
}


======================================================================================================

3.MovieCondition 查詢類

public class MovieCondition {

private String name;
private Type typeset;
private String actor;
private String author;
private Integer smallprice;
private Integer bigprice;

}


======================================================================================================

4.Movie實體類

public class Movie implements java.io.Serializable {


// Fields


private Integer movId;
private String movName;
private String movAuthor;
private Integer movPrice;
private Date movDate;
private String movActor;
private Set<Type> settype=new HashSet<Type>();


======================================================================================================

5. Type 實體類

public class Type  implements java.io.Serializable {

private Integer typeid;
private String typename;
Set<Movie> setmovie=new HashSet<Movie>();


======================================================================================================

6.底層多條件查詢movie方法

public  List<Movie> check(MovieCondition hc){
Criteria criteria = null;
Session session=null;
List<Movie> list =null;
try {
session=HibernateSessionFactory.getSession();
   DetachedCriteria dc = DetachedCriteria. forClass (Movie.class  ); 
   if(hc.getName()!=null){
   dc.add(Restrictions.ilike( "movName",hc.getName(),MatchMode.ANYWHERE)); 
   } if(hc.getActor()!=null){
   dc.add(Restrictions.ilike( "movAuthor",hc.getActor(),MatchMode.ANYWHERE)); 
   } if(hc.getAuthor()!=null){
   dc.add(Restrictions.ilike( "movActor",hc.getAuthor(),MatchMode.ANYWHERE)); 
   }  
   if(hc.getTypeset()!=null){
   Set<Integer> settype=new HashSet<Integer>();
   Typebiz tbi=new ITypebiz();
   Type t=tbi.findById(hc.getTypeset().getTypeid());
   Set<Movie> setmovie=t.getSetmovie();
   System.out.println(setmovie.size());
       Iterator<Movie> it=setmovie.iterator();
   while(it.hasNext()){
   Movie m=it.next();
   settype.add(m.getMovId());
   }
   dc.add(Restrictions.in( "movId",settype)); 
   //dc.add(Restrictions.in( "setid",settype)); 
   } 
   dc.add(Restrictions.ge ( "movPrice",hc.getSmallprice()));
   dc.add(Restrictions.le ( "movPrice",hc.getBigprice()));
  
   Criteria c = dc.getExecutableCriteria(session);
   list = c.list();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}


======================================================================================================

7.多對多關聯新增=----------servlet新增

if("add".equals(opr)){
String name = request.getParameter("name");
String actor = request.getParameter("actor");
String author = request.getParameter("author");
String price = request.getParameter("price");
String[] type = request.getParameterValues("type");
Movie m=new Movie();
m.setMovActor(actor);
m.setMovAuthor(author);
m.setMovDate(new Date());
m.setMovName(name);
m.setMovPrice(Integer.parseInt(price));
Set<Type> s1=new HashSet<Type>();
for(String s:type){
Integer i=Integer.parseInt(s);
Type t=tbi.findById(i);
s1.add(t);
}
m.setSettype(s1);
mbi.save(m);
response.sendRedirect( "MovieServlet?opr=list");
//request.getRequestDispatcher("MovieServlet?opr=list").forward(request, response);
}


======================================================================================================

8.多對多關聯新增=----------底層方法

public void save(Movie m) {
Session session = null;
try {
session = HibernateSessionFactory.getSession();
  session.save(m);
} catch (org.hibernate.HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


======================================================================================================

9.多對多關聯新增=----------對映檔案1

<hibernate-mapping>
    <class name="com.yunhe.entity.Movie" table="MOVIE" schema="SCOTT">
        <id name="movId" type="java.lang.Integer">
            <column name="MOVID" precision="4" scale="0" />
            <generator class="increment" />
        </id>
        <property name="movName" type="java.lang.String">
            <column name="MOVNAME" length="20"  unique="true" />
        </property>
        <property name="movAuthor" type="java.lang.String">
            <column name="MOVAUTHOR" length="20" />
        </property>
        <property name="movPrice" type="java.lang.Integer">
            <column name="MOVPRICE" precision="20" scale="0" />
        </property>
        <property name="movDate" type="java.util.Date">
            <column name="MOVDATE" length="7" />
        </property>
        <property name="movActor" type="java.lang.String">
            <column name="MOVACTOR" length="20"  />
        </property>
        <set name="settype" table="MVOIE_TYPE" >
        <key column="tmmovieid"></key>
        <many-to-many class="com.yunhe.entity.Type" column="tmtypeid"></many-to-many>
        </set>
    </class>
</hibernate-mapping>


======================================================================================================

9.多對多關聯新增=----------對映檔案2

<hibernate-mapping>
    <class name="com.yunhe.entity.Type" table="typess" schema="SCOTT">
        <id name="typeid" type="java.lang.Integer">
            <column name="typeid" precision="4" scale="0" />
            <generator class="increment" />
        </id>
        <property name="typename" type="java.lang.String">
            <column name="typename" length="20" unique="true" />
        </property>
        <set name="setmovie" table="MVOIE_TYPE" cascade="all"  >
        <key column="tmtypeid"></key>
        <many-to-many class="com.yunhe.entity.Movie" column="tmmovieid"></many-to-many>
        </set> 
    </class>
</hibernate-mapping>


======================================================================================================

10.index頁面,實現所有的顯示以及相關的控制,多條件查詢結果的顯示

<c:if test="${!(param.opt eq 'chk')}">
<c:if test="${empty listMovie}">
<%
response.sendRedirect("MovieServlet?opr=list");
%>
</c:if>
</c:if>
<body>

<table width="940" height="98" border="1">


<tr>
<th width="144" align="center">
電影名稱
</th>
<th width="294" align="center">
電影型別
</th>
<th width="121" align="center">
主演
</th>
<th width="108" align="center">
導演
</th>
<th width="125" align="center">
價格
</th>
<th width="208" align="center">
釋出時間
</th>
</tr>
<c:choose>
<c:when test="${fn:length(listMovie)==0}">
<td colspan="6" align="center">


&nbsp;暫無相關影視資訊,請重新查詢!






</td>
</c:when>
<c:otherwise>
<c:forEach items="${listMovie}" var="movie" varStatus="status">
<tr>
<td align="center">
<a href=#>&nbsp;${movie.movName }</a>
</td>
<td align="center">
<c:forEach items="${movie.settype }" var="type"
varStatus="status">${type.typename}&nbsp;&nbsp;</c:forEach>


</td>
<td align="center">
&nbsp;${movie.movActor }
</td>
<td align="center">
&nbsp;${movie.movAuthor }
</td>
<td align="center">
&nbsp;¥${movie.movPrice}.00
</td>
<td align="center">
&nbsp;${movie.movDate }
</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>


<tr>
<td colspan="3" align="center">
&nbsp;
</td>
<td align="center">
<a href="MovieServlet?opr=list">查詢所有資訊</a>
</td>
<td align="center">
<a href="sselect.jsp">查詢相關資訊</a>
</td>
<td align="center">
<a href="add.jsp">釋出最新資訊</a>
</td>
</tr>
</table>
</body>
</html>



相關推薦

Mysql之一查詢如何將條記錄合併成一條記錄

資料庫環境:mysql5.6 需求描述(圖1): 最終期望的結果(圖2): 如上圖所示,現有兩張表cj_lottery_winning_record和cj_lottery_winning_user_info 兩者的關係是一對多。 現在進行連線查

Hibernate的關聯關係對映之一對映

1. 編寫客戶和聯絡人的JavaBean程式(注意一對多的編寫規則) * 客戶的JavaBean如下 public class Customer { private Long cust_id; private String cust_name; private Lo

laraval 條件搜尋laraval分頁攜帶引數

$page= intval($request->input('page'))>1?$request->input('page'):1; //排序 最新 熱門 $orderby=$request->input('orderby');

sql 條件顯示case when then else edn詳細說明。

真的頭痛啊。為此語句,這樣記憶最好,如下: 遇到                XXX情況  就     XXX     遇不到就 XXX    結束 case when     ……       then    ……     else          ……  end

C#完整的通訊程式碼(點同步非同步UDPTCP)

C# code namespace UDPServer { class Program { static void Main(string[] args) { int recv; byte[] data = new byte[1024]; //構建TCP 伺服器 //得到本機IP,設定TCP埠號 IPEnd

Spring Boot2(十一):Mybatis使用總結(自增長、條件、批量操作、查詢等等)

一、前言 上次用Mybatis還是2017年做專案的時候,已經很久過去了。中途再沒有用過Mybatis。導致現在學習SpringBoot過程中遇到一些Mybatis的問題,以此做出總結(XML極簡模式)。當然只是實用方面的總結,具體就不深究♂了。這裡只總結怎麼用!!! (這次直接跳到十一,是因為中間是Rabb

一個php腳本執行中實例次PDO會建立次數據庫連接。

重用 slist OS play 類實例化 每次 連接 inf log 腳本代碼: <?php try { $dbh = new PDO(‘mysql:host=localhost;dbname=test‘, ‘root‘, ‘root‘); } ca

關於抖音如何熱門怎麼上推薦獲取更的流量獲取更的抖音粉絲

抖音如何上熱門?自然漲粉絲,抖音直播教程技巧 抖音已經成為當下年輕人最喜愛的短視訊軟體,不知道愛拍攝短視訊的你知道抖音怎麼上熱門,抖音如何“刷”粉絲嗎?抖音刷粉絲最好的方法你的抖音視訊就是上熱門,得到官方的推薦。 1.原創優質的抖音視訊 2.點贊量=使用者

Linux下佈置個Tomcat同時執行個Tomcat。

轉載這個老哥的https://www.cnblogs.com/webcc/archive/2012/08/22/2651084.html扣號內是我自己操作時的一些問題和決解方法。環境說明:作業系統:  RedHet 5.3JDK版本:  1.4.2WEB容器:    Tomc

maven工程應用spring MAVEN個子模組之間的呼叫

1、ps系統中有兩個模組ps-admin和ps-service,ps-admin負責前臺展示,ps-service負責後臺資料處理,ps的多模組部署pom.xml配置如下: <project xmlns="http://maven.apache.org/POM/4

一次替換個詞批量替換個字串(使用不了的解決辦法)

三天前上CSDN,發現有人回覆批量替換多個詞的工具使用不了。下載下來試用了一下,確實報錯,這兩天打算做個網頁版本的,排版佈局還沒弄好。 上貼回覆以前工具使用不了的解決辦法:下載32位的jre,然後配置JAVA_HOME。 2、下載完畢解壓後,假如路徑(自

Windows下Git賬號配置同一電腦個ssh-key的管理

這一篇文章是對上一篇文章《Git-TortoiseGit完整配置流程》的拓展,所以需要對上一篇文章有所瞭解,當然直接往下看也可以,其中也有一些提到一些基礎的操作。 本文以配置github.com

iOS自定義變數函式如何獲取變數

- (instancetype)initWithTitle:otherButtonTitles, ... { NSMutableArray *buttonTitleArray = [NSMuta

Spring JPA查詢JPA 根據方法名字查詢詳細介紹

 JPA  的查詢有很多豐富的API,基本能滿足了所有的基本查詢。下面來想細說說支援的查詢方式。 根據方法名字生成SQL語句(根據方法名查詢)。 public interface UserRepository extends Repository<User,

mongoDB查詢高階查詢含java操作mongo查詢

     MongoDB是一個基於分散式檔案儲存的資料庫。由C++語言編寫。旨在為WEB應用提供可擴充套件的高效能資料儲存解決方案。      MongoDB是一個介於關係資料庫和非關係資料庫之間的產

折半查詢和遞迴折半查詢詳解(二分法查詢遞迴二分法查詢

演算法:當資料量很大適宜採用該方法。採用二分法查詢時,資料需是排好序的。(前提) 主要思想是:(設查詢的陣列區間為array[low, high]) (1)確定該區間的中間位置K (2)將查詢的值T與

資料結構 折半遞迴查詢二叉排序樹查詢

實驗題目:         查詢演算法實現與分析              實驗環境:     Visual C++ 6.0                     實驗專案七:查詢演算法實現與分析  實驗目的:1.掌握順序表的查詢方法,尤其是二分查詢方法。       

js操作dom節點建立,複製,刪除,新增,查詢等操作總結

1.建立節點 document.createElement(“div”);//建立一個div元素,引數需要是標籤名; document.createTextNode(“233”);//建立一個文

efcore 跨表查詢實現一個介面內查詢兩個不同資料庫裡各自的表資料

  最近有efcore跨庫查詢的需求,研究了下colder框架裡文件的分庫實現,發現並不能完全實現一個介面下的跨庫查詢請求,只能滿足一個業務層構造指定的唯一一個數據庫訪問介面。 先說下文件是怎麼實現的 DbAccessor實現使用多資料庫 預設框架會自動注入IDbAccessor作為資料庫訪問介面,在需要的時

Hibernate-----條件查詢新增查詢案例

====================================================================================================== 1.表單輸入條件  <body>    <form