java

位置:IT落伍者 >> java >> 浏览文章

hibernate入门配置


发布日期:2020年06月18日
 
hibernate入门配置

HibernateUtiljava

package easewirelessgroupsmshbntutil;

import netsfhibernateHibernateException;

import netsfhibernateSession;

import netsfhibernatecfgConfiguration;

/**

* Configures and provides access to Hibernate sessions tied to the

* current thread of execution Follows the Thread Local Session

* pattern see {@link }

*/

public class HibernateUtil {

/**

* Location of hibernatecfgxml file

* NOTICE: Location should be on the classpath as Hibernate uses

* #resourceAsStream style lookup for its configuration file That

* is place the config file in a Java package the default location

* is the default Java package<br><br>

* Examples: <br>

* <code>CONFIG_FILE_LOCATION = /nfxml

* CONFIG_FILE_LOCATION = /com/foo/bar/nfxml</code>

*/

private static String CONFIG_FILE_LOCATION = /hibernatecfgxml;//hibernatecfgxml

/** Holds a single instance of Session */

private static final ThreadLocal threadLocal = new ThreadLocal();

/** The single instance of hibernate configuration */

private static final Configuration cfg = new Configuration();

/** The single instance of hibernate SessionFactory */

private static netsfhibernateSessionFactory sessionFactory;

/**

* Returns the ThreadLocal Session instance Lazy initialize

* the <code>SessionFactory</code> if needed

*

* @return Session

* @throws HibernateException

*/

public static Session currentSession() throws HibernateException {

Session session = (Session) threadLocalget();

&nbsp; if (session == null) {

if (sessionFactory == null) {

try {

nfigure(CONFIG_FILE_LOCATION);

//nfigure();

sessionFactory = cfgbuildSessionFactory();

}

catch (Exception e) {

Systemerrprintln(%%%% Error Creating SessionFactory %%%%);

Systemerrprintln(||||||||||||| + egetMessage());

eprintStackTrace();

}

}

session = sessionFactoryopenSession();

threadLocalset(session);

}

return session;

}

/**

* Close the single hibernate session instance

*

* @throws HibernateException

*/

public static void closeSession() throws HibernateException {

Session session = (Session) threadLocalget();

threadLocalset(null);

if (session != null) {

sessionclose();

}

}

/**

* Default constructor

*/

private HibernateUtil() {

}

}

建表

cat表

代码

CREATE TABLE cat (

cat_id varchar() NOT NULL

NAME varchar() NOT NULL

sex CHAR()

weight FLOAT

PRIMARY KEY (cat_id)

);

po层(系统以cathbmxml为准一个xml可以写多个class)

Xml代码

<<<<<<<<<<<<<cathbmxml>>>>>>>>>>>>>>>>>>>>>>>

<?xml version=?>

<!DOCTYPE hibernatemapping PUBLIC //Hibernate/Hibernate Mapping DTD//EN mappingdtd>

<hibernatemapping>

<class name=easewirelessgroupsmshbntpoCat table=cat>

<id name=id type=string unsavedvalue=null >

<column name=cat_id sqltype=varchar() notnull=true/>

<generator class=uuidhex/>

</id>

<property name=name>

<column name=NAME sqltype=varchar() notnull=true/>

</property>

<property name=sex/>

<property name=weight/>

</class>

</hibernatemapping>

Java代码

<<<<<<<<<<<<<Catjava>>>>>>>>>>>>>>>>>>>>>>>>>

package easewirelessgroupsmshbntpo;

public class Cat {

private String id;

private String name;

private char sex;

private float weight;

public Cat() {

}

public String getId() {

return id;

}

public void setId(String id) {

thisid = id;

}

public String getName() {

return name;

}

public void setName(String name) {

thisname = name;

}

public char getSex() {

return sex;

}

public void setSex(char sex) {

thissex = sex;

}

public float getWeight() {

return weight;

}

public void setWeight(float weight) {

thisweight = weight;

}

public String toString() {

String strCat = new StringBuffer()

append(thisgetId())append( )

append(thisgetName())append( )

append(thisgetSex())append( )

append(thisgetWeight())

toString();

return strCat;

}

}

hibernatecfgxml

(切切不要自己去加属性基本的就两个connectiondatasource和dialect)

Xml代码

<property name=connectionusername>root</property>

<property name=connectionpassword>root</property>

<property name=connectionprovider_class>nnectionDatasourceConnectionProvider</property>

<property name=jndiclass>orggjtmmmysqlDriver</property>

<<<<<<<<<<<<<hibernatecfgxml>>>>>>>>>>>>>>>>>>>>>>>

<?xml version= encoding=UTF?>

<!DOCTYPE hibernateconfiguration PUBLIC

//Hibernate/Hibernate Configuration DTD //EN

configurationdtd>

<! DO NOT EDIT: This is a generated file that is synchronized >

<! by MyEclipse Hibernate tool integration >

<hibernateconfiguration>

<sessionfactory>

<! properties >

<property name=connectiondatasource>java:comp/env/jdbc/test</property>

<property name=show_sql>true</property>

<property name=dialect>netsfhibernatedialectMySQLDialect</property>

<! mapping files >

<mapping resource=com/netease/wireless/groupsms/hbnt/po/cathbmxml/>

</sessionfactory>

</hibernateconfiguration>

测试servlet

//Session生成/关闭

Java代码

<<<<<<<<<<<<<测试HbntTestSvltjava>>>>>>>>>>>>>>>>>>>>>>>

/*

*

* @(#)rpsms V

* Copyright NetEase Inc All rights reserved

*

* coder: sweater

* email:

*

* graphic designer:

* email:

*

* fuction向电话薄中添加组和电话号码

*

*/

package easewirelessgroupsmsvo;

import javaioIOException;

import javaioPrintWriter;

import javautilIterator;

import javaxservletServletException;

import javaxservlethttpHttpServlet;

import javaxservlethttpHttpServletRequest;

import javaxservlethttpHttpServletResponse;

import netsfhibernateHibernateException;

import netsfhibernateQuery;

import netsfhibernateSession;

import netsfhibernateTransaction;

import easewirelessgroupsmshbntpoCat;

import easewirelessgroupsmshbntutilHibernateUtil;

/**

*

* @author sweater

*/

public class HbntTestSvlt extends HttpServlet {

/**

* Constructor of the object

*/

public HbntTestSvlt() {

super();

}

/**

* Destruction of the servlet <br>

*/

public void destroy() {

superdestroy(); // Just puts destroy string in log

// Put your code here

}

/**

* The doGet method of the servlet <br>

*

* This method is called when a form has its tag value method equals to get

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void doGet(HttpServletRequest request HttpServletResponse response)

throws ServletException IOException {

responsesetContentType(text/html);

PrintWriter out = responsegetWriter();

outprintln(<html>);

outprintln(<head>);

outprintln(<title>Hello Hibernate</title>);

outprintln(</head>);

outprintln(<body>);

outprintln(Hello Hibernate!<br>);

try {

Session session = HibernateUtilcurrentSession();

Transaction tx = sessionbeginTransaction();

Query query = sessioncreateQuery(select cat from Cat as cat where catsex = :sex);

querysetCharacter(sex F);

for (Iterator it = erate(); ithasNext();) {

Cat cat = (Cat) itnext();

outprintln(Cat: + cattoString() + <br>);

}

mit();

HibernateUtilcloseSession();

} catch (HibernateException e) {

Systemoutprintln(egetMessage());

//Systemoutprintln(eprintStackTrace());

}

outprintln(</body>);

outprintln(</html>);

}

/**

* The doPost method of the servlet <br>

*

* This method is called when a form has its tag value method equals to post

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void doPost(HttpServletRequest request HttpServletResponse response)

throws ServletException IOException {

responsesetContentType(text/html);

PrintWriter out = responsegetWriter();

outprintln(<!DOCTYPE HTML PUBLIC \//WC//DTD HTML Transitional//EN\>);

outprintln(<HTML>);

outprintln( <HEAD><TITLE>A Servlet</TITLE></HEAD>);

outprintln( <BODY>);

outprint( This is );

outprint(thisgetClass());

outprintln( using the POST method);

outprintln( </BODY>);

outprintln(</HTML>);

outflush();

outclose();

}

/**

* Returns information about the servlet such as

* author version and copyright

*

* @return String information about this servlet

*/

public String getServletInfo() {

return This is my default servlet created by Eclipse;

}

/**

* Initialization of the servlet <br>

*

* @throws ServletException if an error occure

*/

public void init() throws ServletException {

// Put your code here

}

}

Xml代码

<<<<<<<<<<<<<该servlet使用时的webxml>>>>>>>>>>>>>>>>>>>>>>>

<?xml version= encoding=UTF?>

<webapp version=

xmlns=

xmlns:xsi=instance

xsi:schemaLocation=

app__xsd>

<servlet>

<description>hbnttest</description>

<displayname>hbnttest</displayname>

<servletname>HbntTestSvlt</servletname>

<servletclass>easewirelessgroupsmsvoHbntTestSvlt</servletclass>

</servlet>

<servletmapping>

<servletname>HbntTestSvlt</servletname>

<urlpattern>/servlet/HbntTestSvlt</urlpattern>

</servletmapping>

</webapp>

</SPAN< p>

上一篇:如何在Spring中解决中文乱码的方法

下一篇:浅谈Struts2分页的实现与代码实例