Usage of getHibernateTemplate().find

一、find(String queryString);

 示例:this.getHibernateTemplate().find("from bean.User");

 返回所有User对象

二、find(String queryString , Object value);

 示例:this.getHibernateTemplate().find("from bean.User u where u.name=?", "test");

 或模糊查询:this.getHibernateTemplate().find("from bean.User u where u.name like ?", "%test%");

 返回name属性值为test的对象(模糊查询,返回name属性值包含test的对象)

三、find(String queryString, Object[] values);

 示例:String hql= "from bean.User u where u.name=? and u.password=?"

           this.getHibernateTemplate().find(hql, new String[]{"test", "123"});

 返回用户名为test并且密码为123的所有User对象

---------------------------------

四、findByExample(Object exampleEntity)

 示例:

        User u=new User();   

        u.setPassword("123");//必须 符合的条件但是这两个条件时并列的(象当于sql中的and)   

        u.setName("bb");   

        list=this.getHibernateTemplate().findByExample(u,start,max); 

 返回:用户名为bb密码为123的对象

五、findByExample(Object exampleEntity, int firstResult, int maxResults)

 示例:

       User u=new User();   

       u.setPassword("123");//必须 符合的条件但是这两个条件时并列的(象当于sql中的and)   

       u.setName("bb");   

       list=this.getHibernateTemplate().findByExample(u,start,max);   

 返回:满足用户名为bb密码为123,自start起共max个User对象。(对象从0开始计数)

六、findByNamedParam(String queryString , String paramName , Object value)

Use the following statement to query:

    String queryString = "select count(*) from bean.User u where u.name=:myName";

    String paramName= "myName";

    String value= "xiyue";

    this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);

    System.out.println(list.get(0));

返回name为xiyue的User对象的条数

七、findByNamedParam(String queryString , String[] paramName , Object[] value)

 示例:

    String queryString = "select count(*) from bean.User u where u.name=:myName and u.password=:myPassword";

    String[] paramName= new String[]{"myName", "myPassword"};

    String[] value= new String[]{"xiyue", "123"};

    this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);

    返回用户名为xiyue密码为123的User对象

八、findByNamedQuery(String queryName)

 示例:

   1、首先需要在User.hbm.xml中定义命名查询

        <hibernate-mapping>

             <class>......</class>

             <query name="queryAllUser"><!--此查询被调用的名字-->

                  <![CDATA[

                       from bean.User

                   ]]>

             </query>

        </hibernate-mapping>

    2、如下使用查询:

        this.getHibernateTemplate().findByNamedQuery("queryAllUser");

九、findByNamedQuery(String queryName, Object value)

 示例:

   1、首先需要在User.hbm.xml中定义命名查询

        <hibernate-mapping>

             <class>......</class>

             <query name="queryByName"><!--此查询被调用的名字-->

                  <![CDATA[

                       from bean.User u where u.name = ?

                   ]]>

             </query>

        </hibernate-mapping>

    2、如下使用查询:

        this.getHibernateTemplate().findByNamedQuery("queryByName", "test");

十、findByNamedQuery(String queryName, Object[] value)

 示例:

   1、首先需要在User.hbm.xml中定义命名查询

        <hibernate-mapping>

             <class>......</class>

             <query name="queryByNameAndPassword"><!--此查询被调用的名字-->

                  <![CDATA[

                       from bean.User u where u.name =? and u.password =?

                   ]]>

             </query>

        </hibernate-mapping>

    2、如下使用查询:

        String[] values= new String[]{"test", "123"};

        this.getHibernateTemplate().findByNamedQuery("queryByNameAndPassword" , values);

十一、findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)

Example:

   1、首先需要在User.hbm.xml中定义命名查询

        <hibernate-mapping>

             <class>......</class>

             <query name="queryByName"><!--此查询被调用的名字-->

                  <![CDATA[

                       from bean.User u where u.name =:myName

                   ]]>

             </query>

        </hibernate-mapping>

    2、如下使用查询:

        this.getHibernateTemplate().findByNamedQuery("queryByName" , "myName", "test");

十二、findByNamedQueryAndNamedParam(String queryName, String[] paramName, Object[] value)

Example:

   1、首先需要在User.hbm.xml中定义命名查询

        <hibernate-mapping>

             <class>......</class>

             <query name="queryByNameAndPassword"><!--此查询被调用的名字-->

                  <![CDATA[

                       from bean.User u where u.name =:myName and u.password=:myPassword

                   ]]>

             </query>

        </hibernate-mapping>

    2、如下使用查询:

        String[] names= new String[]{"myName", "myPassword"};

        String[] values= new String[]{"test", "123"};



        this.getHibernateTemplate().findByNamedQuery("queryByNameAndPassword" , names, values);

十三、findByValueBean(String queryString , Object value);

Example:

 1、定义一个ValueBean,属性名必须和HSQL语句中的:后面的变量名同名,此处必须至少有两个属性,分别为myName和myPassword,使用setter方法设置属性值后

     ValueBean valueBean= new ValueBean();

     valueBean.setMyName("test");

     valueBean.setMyPasswrod("123");

 2、

     String queryString= "from bean.User u where u.name=:myName and u.password=:myPassword";

     this.getHibernateTemplate().findByValueBean(queryString , valueBean);

十四、findByNamedQueryAndValueBean(String queryName , Object value);

Example:

  1、首先需要在User.hbm.xml中定义命名查询

        <hibernate-mapping>

             <class>......</class>

             <query name="queryByNameAndPassword"><!--此查询被调用的名字-->

                  <![CDATA[

                       from bean.User u where u.name =:myName and u.password=:myPassword

                   ]]>

             </query>

        </hibernate-mapping>

 2、定义一个ValueBean,属性名必须和User.hbm.xml命名查询语句中的:后面的变量名同名,此处必须至少有两个属性,分别为myName和myPassword,使用setter方法设置属性值后

     ValueBean valueBean= new ValueBean();

     valueBean.setMyName("test");

     valueBean.setMyPasswrod("123");




 3、



     String queryString= "from bean.User u where u.name=:myName and u.password=:myPassword";

     this.getHibernateTemplate().findByNamedQueryAndValueBean("queryByNameAndPassword", valueBean);

The s:iterator of struts2 can traverse any array, collection, etc. in the data stack. The following simple demos: The
s:iterator tag has 3 attributes:
value: the
id of the collection to be iterated : the id of the element in the specified collection
status iteration Element index
1: JSP page definition element writing array or list

<s:iterator value="{'1','2','3','4','5'}" id='number'>
<s:property value='number'/>A
</s :iterator> The
print result is: 1A2A3A4A5A
2: The usage of index
If status is specified, each iteration data has an instance of IteratorStatus, it has the following methods
int getCount() returns the current iteration several elements
int getIndex() Returns the current element index
boolean isEven() of course whether the index is even
boolean isFirst() whether the current element is the first
boolean isLast()
boolean isOdd() whether the current element index is odd
<s:iterator value="('a','b ','c'}" id='char' status='st'>
<s:if test="#st.Even">The
current index is an odd number: <s:property value='#st.index' />
</s:if>
Current element value: <s:property value='char'/>
</s:iterator>
3: The traversal map
value can be directly defined as:
value="#{“1”:"A","2":"b"}"
each element is well separated. The key and value between the elements are separated by a colon
The value can also be the Java.util.Map object in the data stack. The
traversal is written as follows:
<s:iterator value="map" id="id" status="st">
key: <s:property value='key'/ >
value:<s:property vlaue='value'/>
</s:iterator>
Of course, both key and value can make Java Object
3: Traverse the data stack. Simple List class,
List
class Attr{String attrName;String getAttrName (){return “123”;}}
<s:iterator value=“label” id=“id”>
<s:property value="#id.attrName" />
</s:iterator>
Of course the value can also be written as value="%{label}" The label can have.
The attribute List of the operation label can be written as value="%{label.list}", which is equivalent to: getLabel().getList();
4: Traverse 2 lists;
List attrN { color,size,style}
List attrV {red,20,Gay}
The elements of these two lists correspond one to one, and one attrN corresponds to one attrV
<s:iterator value="%{attrN }" id=“id” status=“status”>
index is : <s:property value=‘status.index’/>
attrName is : <s:property value=‘id’/> or <s:property value=’%{id}’/>
attrName is : <s:property value=’%{attrV[#status.index]}’/>
</s:iterator>

Hibernate insert data primary key auto-increment
 oracle certification exam
  Implement Oracle's primary key auto-increment strategy in hibernate
  In many cases, we use Hibernate on the basis of an established database. In oracle, if sequence is used in the established database, you can introduce it into Hibernate according to the following steps:
  1. Create sequence in oracle first
  create sequence seq_id
  minvalue 1
  start with 1
  increment by 1
  cache 20;
  2 When you configure
  
  
  seq_id in your hbm.xml
  
  
  and insert data like this, Hibernate will automatically generate the following statement:
  hibernate: select seq_id.nextval from dual
  hibernate: insert into YXJK.T_YXJK_WHRYTXL (XM0000, ZW0000, LXDH00, SJHM00, DZYJ00 ,
  IP0000, ID0000) values ​​(?, ?, ?, ?, ?, ?, ?)
  automatically generate the next sequence value, and then insert the object into the table.
  When using it, you need to pay attention, Hibernate's requirement for the primary key of the sequence must be shor, long, or integer
  According to hibernate's documentation, there are two ways to achieve automatic growth of the primary key of an entity object.
  The first one: Set the ID growth strategy to sequence, and specify the name of the sequence at the same time. It is best to create a sequence for each table. This approach is just like the automatic growth in MS-SQL and MY-SQL, without the need to create triggers The specific oracle database script and hibernate configuration file are as follows:
  [1] Oracle data table creation script:
  Java code
  1. CREATE TABLE DEPARTMENT (
  2. ID NUMBER(19,0) DEFAULT '0' NOT NULL,
  3. NAME VARCHAR2 (255) NOT NULL,
  4. DESCRIPTION CLOB
  5. );
  6. ALTER TABLE DEPARTMENT ADD CONSTRAINT PRIMARY_0 PRIMARY KEY(ID) ENABLE;
  7. ALTER TABLE DEPARTMENT ADD CONSTRAINT UK_DEPARTMENT_1 UNIQUE (NAME);
  8.
  9. CREATE SEQUENCE DEPARTMENT_ID_SEQ MINVALUE 10000 MAXVALUE 999999999999999999999999 INCREMENT BY 1 NOCYCLE;
  Copy code
  Create the DEPARTMENT table, and create a separate SEQUENCE for the DEPARTMENT table, the name is SEQUENCE_ID_SEQ, there is no need to create a trigger.
  [2] Configuration hibernate mapping file:
  the Java code is
  # <xml Version = "1.0"??>
  #
  #
  #
  #
  #
  # DEPARTMENT_ID_SEQ
  #
  #
  #
  #
  #
  #
  copy the code
  in hibernate mapping file for ID generation strategy selection sequence , Specify the sequence name DEPARTMENT_ID_SEQ. When you save a new object, hibernate will automatically obtain DEPARTMENT_ID_SEQ.NEXTVAL as the ID of the new object and save it to the database, so there is no need to use triggers to generate the ID of the new record.

The second: Set the ID growth strategy to be native, but you need to create a globally used sequence named hibernate_sequence (this name seems to be hibernate's default sequence name, if you don't create it, it will be wrong), and then the ID of each table When generating, use a trigger to obtain hibernate_sequence.CURRVAL as the ID of the new record. The specific oracle database script and hibernate configuration file are as follows:
  [1] Oracle data table creation script:
  Java code
  # CREATE TABLE STAFF (
  # ID NUMBER( 19,0) DEFAULT '0' NOT NULL,
  # NAME VARCHAR2(255) NOT NULL,
  # AGE NUMBER(3,0) NOT NULL,
  # BIRTHDAY DATE NOT NULL,
  # SALARY NUMBER(10,2) NOT NULL,
  # LEVELNESS FLOAT NOT NULL,
  # CREATETIME TIMESTAMP NOT NULL,
  # ENABLE CHAR(2) DEFAULT'Y ' NOT NULL,
  # STATUS VARCHAR2(64) NOT NULL,
  # DEPARTMENT_ID NUMBER(19,0)
  # );
  # ALTER TABLE STAFF ADD CONSTRAINT PRIMARY_1 PRIMARY KEY(ID) ENABLE;
  # ALTER TABLE STAFF ADD CONSTRAINT STAFF_IBFK_0 FOREIGN KEY(DEPARTMENT_ID) REFERENCES DEPARTMENT(ID) ENABLE;
  # ALTER TABLE STAFF ADD CONSTRAINT UK_STAFF_1 UNIQUE (NAME);
  # CREATE INDEX IDX_STAFF_STATUS ON STAFF(STATUS);
  #
  # CREATE SEQUENCE HIBERNATE_SEQUENCE MINVALUE 90000 MAXVALUE 999999999999999999999999 INCREMENT BY 1 NOCYCLE;
  #
  # CREATE OR REPLACE TRIGGER STAFF_ID_TRG BEFORE INSERT ON STAFF
  # FOR EACH ROW
  # BEGIN
  # IF INSERTING AND :NEW.ID IS NULL THEN
  # SELECT HIBERNATE_SEQUENCE.CURRVAL INTO :NEW.ID FROM DUAL;
  # END IF;
  # END;
  复制代码
  Create the STAFF table, but did not create the corresponding primary key sequence for STAFF, but created a sequence named HIBERNATE_SEQUENCE, and then created a trigger STAFF_ID_TRG, when the INSERT operation is executed, hibernate will first execute HIBERNATE_SEQUENCE.NEXTVAL, so in The trigger only needs to obtain HIBERNATE_SEQUENCE.CURRVAL as the ID of the new record.
  [2] Configuration of hibernate mapping file:
  Java code
  # <?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC
 # "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
# "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
# <hibernate-mapping package="com.liyanframework.demo.domain"> 
# <class name="Staff" table="STAFF"> # <id name="id" column="ID">
 # <generator class="native" /> # </id> # <property name="name" column="NAME" type="string" /> # <property name="age" column="AGE" type="integer" /> # <property name="birthday" column="BIRTHDAY" type="date" /> # <property name="salary" column="SALARY" type="big_decimal" /> # <property name="level" column="LEVELNESS" type="float" /> # <property name="createTime" column="CREATETIME" type="timestamp" /> # <property name="enable" column="ENABLE" type="character" /> # <property name="status" column="STATUS" type="string" /> # <many-to-one name="department" column="DEPARTMENT_ID" class="Department" /> # </class> </hibernate-mapping>

In the hibernate mapping file, select native for the ID generation strategy, and hibernate will generate the ID of the new record according to the trigger of your database.
  Comparing the two approaches, the second approach is that hibernate implements the trigger function in oracle in the code. For different situations, choose what you don't understand. If you are a new system or a new oracle database, it is recommended to use the first approach, which is simple and easy to transplant to other databases that support automatic growth; if it is an old system, you need to convert other databases to oracle, then use the second So, using the native way, you can leave the configuration file unchanged and be compatible with databases with automatic growth such as Oracle and MySQL.

Guess you like

Origin blog.csdn.net/qq_43479839/article/details/104846844