Refer to other people's examples of Hibernate
Step 1: Create a table structure as follows:
+ ----------- + -------------- + ------ + ----- + --------- + ---------------- +
| FIELD | type | null | key | default | extra |
+ ----------- + -------------- + ------ + ----- + --------- + ---------------- +
| ID | int (11) | no | Mul | null | auto_increment |
| Title | varchar (400) | Yes | null |
| Content | text | Yes | null |
| Time | datetime | Yes | null |
+ ----------- + -------------- + ------ + ----- + --------- + ---------------- +
Step 2: Create a Java project in eclipse (the package name I used in the project is cn.com. Nick. HBM ). Compile the news. Java class, which corresponds to the table in the database
Package cn.com. Nick. HBM;
Import java. util. date;
Public class News
{
Private int ID;
Private String title;
Private string content;
Private date;
Public int GETID ()
{
Return ID;
}
Public void setid (int id)
{
This. ID = ID;
}
Public String gettitle ()
{
Return title;
}
Public void settitle (String title)
{
This. Title = title;
}
Public String getcontent ()
{
Return content;
}
Public void setcontent (string content)
{
This. content = content;
}
Public date getdate ()
{
Return date;
}
Public void setdate (date)
{
This. Date = date;
}
}
Step 3: Save the configuration correspondence as the news. HBM. xml file and the news class in the same directory (not necessarily in the same directory, so that you can put them here for convenience)
<? 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>
<Hibernate-mapping>
<! -- The cn.com. Nick. HBM. News class corresponds to the news table. The fields and table names in the data sheet are not divided into different sizes. -->
<Class name = "cn.com. Nick. HBM. News" table = "news">
<! -- From here, the attribute in the news class is configured to correspond to the field in the table and the type of this field -->
<ID name = "ID" column = "ID">
<Generator class = "native"/>
</ID>
<! --
The table name and field name in the database are case-insensitive, so these fields can be in upper or lower case column = "title"
-->
<Property name = "title" type = "string" column = "title"/>
<Property name = "content" type = "string" column = "content"/>
<Property name = "date" type = "timestamp" column = "time"/>
</Class>
</Hibernate-mapping>
Step 4: Configure hibernate. cfg. XML note that this name cannot be changed and should be placed under the path of SRC (note that the method in the example of the wrong place cannot find this file)
<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype hibernate-Configuration
Public "-// hibernate/hibernate configuration DTD // en"
Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd>
<Hibernate-configuration>
<Session-factory name = "Java:/hibernate/hibernatefactory">
<Property name = "show_ SQL"> true </property> <! -- Configure to display SQL statements for debugging -->
<Property name = "connection. driver_class">
Com. Microsoft. JDBC. sqlserver. sqlserverdriver <! -- Here is the JDBC Driver Class Name of SQL2000 -->
</Property>
<Property name = "current_session_context_class"> thread </property> <! -- Configuration context -->
<Property name = "connection. url">
JDBC: Microsoft: sqlserver: // localhost: 1433; databasename = test <! -- Here is the URL of the hibernate_test database of SQL2000 -->
</Property>
<Property name = "connection. username"> SA </property> <! -- Username -->
<Property name = "connection. Password"> </property>
<! -- Password -->
<Property name = "dialect">
Org. hibernate. dialect. sqlserverdialect <! -- Here is the dialect of SQL2000 -->
</Property>
<Property name = "myeclipse. Connection. Profile"> my </property>
<Mapping Resource = "cN/COM/Nick/HBM/news. HBM. xml"/> <! -- Specify the ing file of news -->
</Session-factory>
</Hibernate-configuration>
The code for creating a test. Java class is as follows, which contains annotations.
Package cn.com. Nick. HBM;
Import java. util. date;
Import java. util. List;
Import org. hibernate. hibernateexception;
Import org. hibernate. sessionfactory;
Import org. hibernate. cfg. configuration;
Import org. hibernate. Classic. Session;
Public class test {
Private Static final sessionfactory;
Static {
Try {
// Sessionfactory is created here to put the hibernate. cfg. xml file to the path of SRC.
// Hibernate will find it by yourself
Sessionfactory = new configuration (). Configure ()
. Buildsessionfactory ();
} Catch (throwable ex ){
// Make sure you log the exception, as it might be swallowed
System. Err. println ("Initial sessionfactory creation failed." + ex );
Throw new exceptionininitializererror (Ex );
}
}
Public static sessionfactory getsessionfactory (){
Return sessionfactory;
}
Public static void main (string [] ARGs ){
// Instantiate a new news object and fill in the content
News news = new news ();
News. setid (2 );
News. settitle ("Jin Chun ");
News. setcontent ("jinchun every day ");
News. setdate (new date ());
Test T = new test ();
// Call the storage method under the test class, which is equivalent to executing the insert statement
T. Save (News );
// Call the query method to display the database content
System. Out. println ("wwww ");
T. Select ();
// Call the update Method
// T. Update ();
// Call Delete
// T. Delete ();
}
/**
* A Simple Method for adding data
*
* @ Param news
* News object, which will be added to the library
*/
Public void save (News news ){
Try {
// Obtain the hibernate session
Session session = test. getsessionfactory (). getcurrentsession ();
Session. begintransaction ();
// Here, you only need to call the Save method to upload the news object and insert it successfully!
Session. Save (News );
Session. gettransaction (). Commit ();
} Catch (hibernateexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
/**
* Query Method
*/
Public void select (){
Try {
Session session = test. getsessionfactory (). getcurrentsession ();
Session. begintransaction ();
// Note !!! The news here is not the table name! It is the object name, so pay attention to Case sensitivity.
String SQL = "from News ";
// Conditional Query
// String SQL = "from news where id = 1 ";
// Use session. createquery () to execute the hql query statement
List <News> L = session. createquery (SQL). List ();
// Cyclically output in the console
For (News N: l ){
System. Out. println (N. GETID ());
System. Out. println (N. gettitle ());
System. Out. println (N. getcontent ());
System. Out. println (N. getdate ());
System. Out. println ("================ ");
}
Session. gettransaction (). Commit ();
} Catch (hibernateexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
/**
* Update Method
*/
Public void Update (){
Try {
Session session = test. getsessionfactory (). getcurrentsession ();
Session. begintransaction ();
// Defines the ID of the object to be loaded
Integer id = 1;
// Load an object
News n = (News) Session. Load (news. Class, new INTEGER (ID ));
// Reset the object title
N. settitle ("updated title ");
// Update this object using the update Method
Session. Update (N );
Session. gettransaction (). Commit ();
} Catch (hibernateexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
Public void Delete (){
Try {
Session session = test. getsessionfactory (). getcurrentsession ();
Session. begintransaction ();
// Defines the ID of the object to be loaded
Integer id = 6;
// Load an object
News n = (News) Session. Load (news. Class, new INTEGER (ID ));
// Delete the object using the delete Method
Session. Delete (N );
Session. gettransaction (). Commit ();
} Catch (hibernateexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
Public void delete1 (){
Session session = test. getsessionfactory (). getcurrentsession ();
Session. begintransaction ();
Integer id = 6;
News n = (News) Session. Load (news. Class, new INTEGER (ID ));
Session. Delete (N );
Session. gettransaction (). Commit ();
}
}
Examples of JSP upload and download complexity
1 upload. the JSP file is as follows:
<Form action = "Servlet/upload" method = "Post">
<Input type = "file" name = "file1">
<Br>
<Input type = "file" name = "file2">
<Br>
<Input type = "file" name = "file3">
<Input type = "Submit" value = "Upload"/>
<Br>
<Br>
<A href = "Servlet/down? Downfile1_tutorial tutorial. Doc "> down </a>
</Form>
2. Write the following code in the servlet (upload. Java) dopost:
Response. setcontenttype ("text/html; charset = gb2312 ");
// File name to download
// This is mainly because of cultural issues in the file name. In this way, the Chinese file name will be displayed normally.
String AA = new string (request. getparameter ("file1 "))
. Getbytes ("iso8859-1"), "gb2312 ");
String BB = new string (request. getparameter ("file2 "))
. Getbytes ("iso8859-1"), "gb2312 ");
String cc = new string (request. getparameter ("file3 "))
. Getbytes ("iso8859-1"), "gb2312 ");
List <string> List = new arraylist <string> ();
If (Aa! = NULL |! AA. Equals (""))
List. Add (AA );
If (! BB. Equals ("") | BB! = NULL)
List. Add (bb );
If (CC! = NULL |! Cc. Equals (""))
List. Add (CC );
// Create a path for storing uploaded files
File uploadpath = new file (request. getrealpath ("/downloadpath "));
System. Out. println (uploadpath );
If (! Uploadpath. exists ()){
Uploadpath. mkdirs ();
}
For (INT I = 0; I <list. Size (); I ++ ){
String filename [] = new string [list. Size ()];
String exfilename [] = new string [list. Size ()];
// File path
String filepath = list. Get (I );
// Obtain the name of the uploaded file
Filename [I] = filepath. substring (filepath. lastindexof ("//") + 1,
Filepath. Length ());
// Retrieve the extension name of the file
// Exfilename [I] = filepath. substring (filepath. lastindexof ("." + 1,
// Filepath. Length ()));
// Create a file in the stored directory
File uploadfilename = new file (uploadpath, filename [I]);
If (! Uploadfilename. exists ()){
Uploadfilename. createnewfile ();
}
Fileinputstream fin = new fileinputstream (filepath );
// Write files to the server
Java. Io. fileoutputstream Fos = new java. Io. fileoutputstream (uploadpath + "/" + filename [I]);
Int c = fin. Read ();
While (C! =-1 ){
FOS. Write (char) C );
C = fin. Read ();
}
Fin. Close ();
FOS. Close ();
}
4. The code for downloading the servlet (down. Java) doget method is as follows:
Response. setcontenttype ("text/html; charset = gb2312 ");
Httpsession session = request. getsession ();
// File name to download
String downloadfile = new string (request. getparameter ("downfile "))
. Getbytes ("iso8859-1"), "gb2312 ");
Servletcontext context = getservletcontext ();
Servletconfig Config = getservletconfig ();
// Obtain the directory of the file to be downloaded. The directory corresponds to the physical path on the server.
// The Directory format is as follows:
// Root directory (the actual physical directory corresponding to the Web main directory)
// + Virtual directory (subdirectory of the downloaded file)
String downloadpath = context. getrealpath (file. separator)
+ "Downloadpath" + file. Separator;
System. Out. println (downloadpath );
// Construct the object of the downloaded object
Java. Io. File file = new java. Io. File (downloadpath + downloadfile );
// Obtain the object Length
Long filesize = file. Length ();
// Set the output format
Response. addheader ("Content-Type", "application/X-msdownload ;");
Response. addheader ("content-disposition", "attachment; filename ="
+ Response. encodeurl (downloadfile); // The save file name to be displayed in the SAVE window
Response. addheader ("Content-Length", long. tostring (filesize ));
// Write a file to the client
Java. Io. fileinputstream fin = new java. Io. fileinputstream (File );
Byte [] B = new byte [1];
Int J = 0;
While (j = fin. Read (B)> 0 ){
Response. getoutputstream (). Write (B );
}
Fin. Close ();
3. Web. xml file configuration
<? XML version = "1.0" encoding = "UTF-8"?>
<Web-app version = "2.4"
Xmlns = "http://java.sun.com/xml/ns/j2ee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemalocation = "http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<Servlet>
<Description> This is the description of my J2EE component </description>
<Display-Name> This is the display name of my J2EE component </display-Name>
<Servlet-Name> upload </servlet-Name>
<Servlet-class> com. Upload </servlet-class>
</Servlet>
<Servlet>
<Description> This is the description of my J2EE component </description>
<Display-Name> This is the display name of my J2EE component </display-Name>
<Servlet-Name> down </servlet-Name>
<Servlet-class> com. Down </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-Name> upload </servlet-Name>
<URL-pattern>/servlet/upload </url-pattern>
</Servlet-mapping>
<Servlet-mapping>
<Servlet-Name> down </servlet-Name>
<URL-pattern>/servlet/down </url-pattern>
</Servlet-mapping>
<Welcome-file-List>
<Welcome-File> index. jsp </welcome-File>
</Welcome-file-List>
</Web-app>