Java fooling around notes: Hibernate:1, basic operations

Source: Internet
Author: User
Tags flush rollback

Fooling around after the knowledge Point finishing, the first section, simple to build a database is MySQL, the project is MAVEN, note also comments in the code, the structure is as follows

Main knowledge points (simple example, hql operation, SQL operation)

Pom.xml:

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>com.ywj</groupId> <artifactId> Testhibernate</artifactid> <version>0.0.1-SNAPSHOT</version> <packaging>jar</ Packaging> <name>TestHibernate</name> <url>http://maven.apache.org</url> < Properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties > <dependencies> <dependency> <groupId>junit</groupId> <artifactid>junit</ar tifactid> <version>3.8.1</version> <scope>test</scope> </dependency> <!--h Ttps://mvnrepository.com/artifact/org.hibernate/hibernate-core--> <!--load Hibernate jar--> <Dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> & Lt;version>4.2.21.final</version> </dependency> <!--https://mvnrepository.com/artifact/mysql/
			Mysql-connector-java--> <!--load MySQL driver jar--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency
 > </dependencies> </project>


hibernate.cfg.xml: (hiberante configuration file, the primary role is to configure the database)

<?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 "> Log4j.properties: (log)

Log4j.rootlogger = Info,stdout,warn

Log4j.appender.STDOUT = Org.apache.log4j.ConsoleAppender
Log4j.appender.STDOUT.Target = System.out
log4j.appender.STDOUT.layout = org.apache.log4j.PatternLayout
Log4j.appender.STDOUT.layout.ConversionPattern =%d%p [%c]-%m%n%l 


= Org.apache.log4j.DailyRollingFileAppender
log4j.appender.WARN.File = D:/logs/log.log
Log4j.appender.WARN.layout = org.apache.log4j.PatternLayout
Log4j.appender.WARN.layout.ConversionPattern =%d% p [%c]-%m%n%l 

log4j.appender.INFO = org.apache.log4j.DailyRollingFileAppender
log4j.appender.INFO.File = D :/logs/log.log
log4j.appender.INFO.layout = org.apache.log4j.PatternLayout
User.java: (An object, that is, a table, an object's properties (Id,name ...) Which is the field of the table again)

package com.ywj.testhibernate.e;
Import java.io.Serializable;

Import Java.util.Date; public class User implements serializable{/** * * */private static final long Serialversionuid = 62777071062633403

	56L;
		Public user () {} public user (Long ID, String name) {this.id = ID;
	THIS.name = name;
	Private Long ID;
	private String name;
	Private Integer age;
	Private Date birthday;
	
	Private String IdNumber;
	Public Long GetId () {return id;
	public void SetId (Long id) {this.id = ID;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	Public Integer Getage () {return age;
	public void Setage (Integer age) {this.age = age;
	Public Date Getbirthday () {return birthday;
	The public void Setbirthday (Date birthday) {this.birthday = birthday;
	Public String Getidnumber () {return idNumber;
	} public void Setidnumber (String idNumber) {this.idnumber = IdNumber; }
	
}

User.hbm.xml: (Object configuration file)

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE hibernate-mapping public
        "-//hibernate/hibernate mapping DTD 3.0//en"
        "http:// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">

 

Testsql.java: (SQL operation)

Package com.ywj.TestHibernate.test;


Import java.util.List;
Import Org.hibernate.SQLQuery;
Import org.hibernate.Session;


Import org.hibernate.Transaction;


Import Com.ywj.testhibernate.e.user;
		public class Testsql {/** * @param args */public static void main (string[] args) {session session = NULL;
		Transaction ts = null;
			try {session = Hibernateutils.getcurrentsession ();
			ts = session.begintransaction ();
			Query return object/*string sql = "SELECT * from user";
			SQLQuery sqlquery = session.createsqlquery (sql). addentity (User.class);//object List<user> List = Sqlquery.list ();
				if (!list.isempty ()) {//The following code does not judge the province the matter is actually to be judged for (User u:list) {System.out.println (U.getname ());
			}*///Query return with parameter/*string sql = "SELECT * from user where id =?";
			SQLQuery sqlquery = session.createsqlquery (sql). addentity (User.class);//Object Sqlquery.setparameter (0, 3);
			list<user> list = Sqlquery.list (); for (User u:list) {SystEm.out.println (U.getname ());
			}*///query returns list<map>/*string sql = "Select name,age from User";
			SQLQuery sqlquery = session.createsqlquery (sql);
			Sqlquery.setresulttransformer (CRITERIASPECIFICATION.ALIAS_TO_ENTITY_MAP);
			list<map<string, object>> list = Sqlquery.list ();
			*///query returns some fields/*string sql = "Select name,age from User"; SQLQuery sqlquery = session.createsqlquery (SQL), and/or addentity (user.class) returns list<object[]> format List<Object
			[]> list = Sqlquery.list ();
			For (object[] obj:list) {System.out.println (obj[0]+ ":" +obj[1]);
			}*///query returns a field/*string sql = "SELECT name from User"; SQLQuery sqlquery = session.createsqlquery (sql);//A single field returns the list<object>  list<object> List = SQLQuery
			. List ();
			for (Object obj:list) {System.out.println (obj);
			}*///return quantity/*string sql = "SELECT COUNT (*) from user"; SQLQuery sqlquery = session.createsqlquery (sql);//A single field returns the list<object>  list<object> List = Sqlquery.list (); System.out.println (list.get (0)); *//Add/* String sql = INSERT INTO user (Name,age,birthday,idnumber) value
			S (?,?,?,?) ";
			SQLQuery sqlquery = session.createsqlquery (sql); Sqlquery.setparameter (0, "name");//The first question mark Sqlquery.setparameter (1, 1);//The second question mark Sqlquery.setparameter (2, New Date ());
			The third question mark Sqlquery.setparameter (3, "123");//Fourth question mark Sqlquery.executeupdate (); Ts.commit (); *//modify/*string sql = "Update user set name =?" WHERE id =?
			";
			SQLQuery sqlquery = session.createsqlquery (sql);
			Sqlquery.setparameter (0, "nameup");//The first question mark Sqlquery.setparameter (1, 2);//The first question mark Sqlquery.executeupdate ();
			Ts.commit (); *//delete/*string sql = "Delete from  user where id =?";
			SQLQuery sqlquery = session.createsqlquery (sql);
			Sqlquery.setparameter (0, 4);//The first question mark Sqlquery.executeupdate ();
Ts.commit (); */} catch (Exception e) {e.printstacktrace ();			Ts.rollback ();
			finally {if (session!= null) {session.close ();
 }
		}
	}


}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.