package dao;
import java.util.ArrayList;
import java.util.List; import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Transaction; import com.sun.org.apache.bcel.internal.generic.GETSTATIC; import common.BaseDAO;
import common.DataZh; import entity.Station; //station and ddxx It's a one to many relationship , To keep the code clean , The additions, deletions and changes of each entity are written in its own dao, Complex queries can be written as needed dao in
public class StationDAO extends BaseDAO<Station> { //////////////////////////////////////////////////////////////// demonstration hql Inquire about
// Use Hql Query station name contains " Beijing " Word of all sites
public List findByproperty(String propertyName) { // Pass the parameter through the place holder
String querystring = "from Station as model where model.czmc like ?"; // Display parameters
// String
// querystring="from Station as model where model.czmc like '%"+propertyName+"%'"; Query queryObject = gs().createQuery(querystring); queryObject.setParameter(0, "%" + propertyName + "%"); // The ginseng return queryObject.list();
} // The last word of the query is " Beijing " Words and grades are " First class " All sites
public List findByKey(String Key1, String Key2) { String querystring = "from Station as model where model.czmc like ? and model.dj=?"; // Display parameters
// String
// querystring="from Station as model where model.czmc like '%"+propertyName+"%'"; Query queryObject = gs().createQuery(querystring); queryObject.setParameter(0, "%" + Key1);
queryObject.setParameter(1, Key2); // The ginseng return queryObject.list();
} // By judging the dynamic combination of parameters Hql sentence , Generate basic general queries
public List find(Station entity) {
List reuslt = null; // String auxiliary class
StringBuffer hql = new StringBuffer("from Station where 1=1"); List vp = new ArrayList(); if (entity != null) { // Less than 0 And null No comparison
if (entity.getCzdm() != null && entity.getCzdm() < 0) {
hql.append(" and czdm=?");
vp.add(entity.getCzdm());
} // Empty string and null No comparison
if (entity.getCzmc() != null && entity.getCzmc().length() > 0) {
hql.append(" and czmc = ?");
vp.add(entity.getCzmc());
} if (entity.getDj() != null) {
hql.append(" and dj=?");
vp.add(entity.getDj());
}
} Query q = gs().createQuery(hql.toString()); for (int i = 0; i < vp.size(); i++) {
q.setParameter(i, vp.get(i));
} reuslt = q.list();
return reuslt;
} //////////////////////////////////////////////////////////////// Demonstrate complex queries // Use native sql, According to the level of fuzzy query to meet the conditions of all the station names
public List<String> findonebydj(String dj) {
// sql sentence
String sql = "select czmc from station where dj like '%" + dj + "%'"; SQLQuery q = gs().createSQLQuery(sql); return DataZh.ObjtoStr(q.list());
} // Use native sql, According to the level of fuzzy query to meet the conditions of all the station name and station code
public List<String[]> findmanybydj(String dj) {
// sql sentence
String sql = "select czmc,czdm from station where dj like '%" + dj
+ "%'"; SQLQuery q = gs().createSQLQuery(sql); return DataZh.ObjArrtoStrArr(q.list());
} // Use native sql, Connect two tables station,ddxx, Check all orders from Guangzhou East id, state , Grade
public List<String[]> findmanysbydj(String dj) {
// sql sentence
String sql = "select a.czmc,id,b.status,dj from station a,ddxx b where a.czdm=b.czid and a.czmc='"
+ dj + "'"; SQLQuery q = gs().createSQLQuery(sql);
return DataZh.ObjArrtoStrArr(q.list());
} //////////////////////////////////////////////////////////////// Demonstrate complex delete // Enter the station code , Delete all related stations and orders
public int excuteFzDelete(Integer id) { // Delete separately
String sql = "delete from station where czdm=" + id;
String sql2 = "delete from ddxx where czid=" + id; // Adding, deleting and changing need to be done , The transaction start
Transaction tx = null;
tx = gs().beginTransaction(); SQLQuery q = gs().createSQLQuery(sql); int a = q.executeUpdate(); SQLQuery q2 = gs().createSQLQuery(sql2);
int b = q2.executeUpdate(); tx.commit(); // Commit transaction if (a > 0 || b > 0) // Valid deletion returns 1
return 1;
else
return 0; // Invalid deletion returns 0 } //////////////////////////////////////////////////////////////// Demonstrate complex updates // All invalid ( The station no longer exists ) Order all stations ID(czid) All updated to the designated station ID // Complex updates , need inner join
//update ddxx a INNER JOIN
//(select id from ddxx where czid not in(select DISTINCT czdm from station)) as b
//ON a.id=b.id set czid=222
public int excuteFzUpdate(Integer czid)
{
StringBuffer s=new StringBuffer();
s.append("update ddxx a INNER JOIN");
s.append("(select id from ddxx where czid not in(select DISTINCT czdm from station)) as b");
s.append(" ON a.id=b.id set czid="+czid); // Add, delete, change and add
Transaction tx;
tx=gs().beginTransaction();
SQLQuery q=gs().createSQLQuery(s.toString()); // Rows affected
int a=q.executeUpdate();
tx.commit();
return a;
} //////////////////////////////////////////////////////////////// Show many to many /*
* Site (Station) And the lines (Line) It's a many to many relationship ,
* In the database , The solution is to break it into three tables , Make a middle table , The middle table should contain the primary keys of two main tables
* Many to many split into two one to many
*
*/ // Query the name of all lines passing through the specified station
public List<String> searchLineByStation(String czmc)
{
String sql = "select xlmc from line where xlid in (select a.LID from stationjoinline a,station b where a.SID = b.czdm and b.czmc=?)";
SQLQuery q=gs().createSQLQuery(sql); // It is recommended to use setParameter Add parameters
q.setParameter(0, czmc);
return DataZh.ObjtoStr(q.list());
} // Query the name of all stations that the specified line passes through , Site ID
public List<String[]> searchStationByLine(String xlmc)
{
String sql="SELECT * from station c WHERE c.czdm IN"+
"(SELECT b.SID FROM stationjoinline b WHERE b.LID IN"+
"(SELECT a.xlid FROM line a WHERE a.xlmc=?))";
SQLQuery q=gs().createSQLQuery(sql);
q.setParameter(0, xlmc);
List<String[]> list=q.list();
return DataZh.ObjArrtoStrArr(q.list());
} ////////////////////////////////////////////////////////////dao summary
/*
* summary :
*
* -------------------------------------- Inquire about
* 1.hql Inquire about
*
* StringBuffer hql = new StringBuffer("from Station where 1=1");
*
* Query q = gs().createQuery(hql.toString());
*
* q.list();
*
* 2.sql Inquire about
*
* String sql = "select czmc,czdm from station where dj like '%" + dj
+ "%'"; SQLQuery q = gs().createSQLQuery(sql); //sql Query usage createSQLQuery q.list();
*
* DataZh.ObjArrtoStrArr(q.list()) //sql The query returns Object, Remember to switch
*
*
* -------------------------------------- Additions and deletions
* Use native sql Statement execution
*
* String sql = "delete from station where czdm=" + id;
*
* Transaction tx = null;
tx = gs().beginTransaction(); SQLQuery q = gs().createSQLQuery(sql); * tx.commit(); // Commit transaction
*
* q.executeUpdate() // Add, delete, and modify statements using this function
*
* return result // Returns the number of affected rows
*
*/ }

hibernate Add, delete, change and check demo More articles about

  1. SSH Login, add, delete, change and search demo Detailed explanation + Source code

    Click to download , Tests are absolutely available SSH Integration framework login, add, delete, modify and query demo Download address :http://download.csdn.net/detail/qq_33599520/9784679   One . The framework outlined spri ...

  2. 【 Outline of handout 】 With a real news cms Additions and deletions demo For example , Train the national innovation team of the college php

    PHP Practical basis —— With a piece of news cms For example One .        Environment configuration Two .        Database creation 3、 ... and .        Additions and deletions demo Connect to database <?php $link=mysq ...

  3. mvc Pattern jsp+servel+dbutils oracle Basically add, delete, change and check demo

    mvc Pattern jsp+servel+dbutils oracle Basically add, delete, change and check demo Download address

  4. mvc Pattern jsp+servel+jdbc oracle Basically add, delete, change and check demo

    mvc Pattern jsp+servel+jdbc oracle Basically add, delete, change and check demo Download address

  5. ssm Study ( Four )-- Complete additions, deletions, changes and queries demo

    The last article briefly introduced that sping mvc Join the whole framework , It's finished ssm Integration of . This section continues with the previous , combination spring mvc Do a simple addition, deletion, modification and query demo. 1. First , Rewrite GeckoList.jsp page ...

  6. ztree-- Add, delete, modify and check the plug-in demo( Full version )

    ztree-- Add, delete, modify and check the plug-in demo( Full version ) var setting = {                 async: {                     enable: true,  ...

  7. EasyUI + Spring MVC + hibernate Add, delete, modify, query, import and export

    ( It's a story --) Preface As a JAVA Development Engineer , I think the most basic thing is to understand the front end . Backstage and database . The content of the exercise is very basic , Include : Basically add, delete, change and check . Fuzzy query . Paging query . Tree menu . Upload and download .tab page The director sent me a message ...

  8. Hibernate A complete set of additions, deletions, changes and checks + Pagination

    1. Create a web engineering 2. Import jar package 3. establish Student surface 4. Create entity class package com.entity; public class Student { private Integer ...

  9. Hibernate Addition, deletion and modification of

    One . build Hibernate development environment , Not here , Let's talk about things after the environment is set up . Two . Directory structure of the project

Random recommendation

  1. python3 String and list common functions

    One . Common string functions 1. capitalize(), Make the first letter of a string uppercase , The rest is in lowercase : If there are multiple words in the string , Just capitalize the first letter of the first word : example : >>> name = ...

  2. Tips find one php Of cron The wrong line of code in the script

    It's a small trick , But it's useful . I wrote one cron Script , But the next day I found out , This is yesterday's cron The script is still running , Didn't stop , There must be a program blocked inside . But if I run again, it will take a lot of time . What about this? ? Now? ...

  3. hadoop 2.6 Pseudo Distributed installation

    hadoop 2.6 Of “ false ” Fractional installation and “ whole ” Fractional installation , Most of the operations are the same , The main difference is that you don't have to configure slaves file , And other xxx-core.xml Many of the parameters in can also be omitted , Here are some key configurations : ( Ann ...

  4. PV UV

    Definition PV: Page View       Page views or hits , Every time the user refreshes it is calculated once . UV: Unique Visitor   It's just how many IP Number . It means how many people are visiting your store . Everyone's computer ...

  5. Spring3.1 Use in profile Configure the development test online environment

    If you do some database testing during development , Want to link to a test database , To avoid the impact on the development of the database . Some configuration during development, such as log4j Level of logging , It's different from the production environment . All kinds of such needs , Let me hope to have a simple switch development ring ...

  6. VBS The basic chapter - The dynamic array

    VBS Dynamic arrays in need to use System.Collections.ArrayList ' Build dynamic array Dim Arrl : Set Arrl = CreateObject("System.Co ...

  7. Tiling( Recurrence + Large number )

    Description In how many ways can you tile a 2xn rectangle by 2x1 or 2x2 tiles? Here is a sample tili ...

  8. Klockwork Alarm common error

    Here's a list of Klockwork The common form of alarm , None of these will report syntax errors during the compilation phase , And the probability of execution in the run phase is very small . But in some scenarios, once these statements are executed ,  It is likely to cause the process to run and hang up .   ...

  9. C# language norm _ edition 5.0 ( The first 21 Chapter appendix C_ Reference material )

    A. Reference material Unicode The Federation .The Unicode Standard, Version 3.0(Unicode standard 3.0 edition ).Addison-Wesley,Reading,Massa ...

  10. take DLL The file is packaged directly into exe In the executive file (C#)

    Preface : Because the project needs , We need to make a registration machine , Will individual PC Of MAC The value and the serial number of the hard disk are bound to the software , Because of my C++ Is not very good , So using C# Development . But using C# When , Get the hard disk MAC The value and serial number are not very accurate , ...