新建一个JavaProject(不一定非要web工程)
在工程里面新建一个文件夹lib,用来存放jar包

添加到咱们建好的lib文件夹里面
Hibernate下载地址http://hibernate.org/orm/downloads/
还需要的就是jdbc驱动包 mysql-connector-java-5.1.37-bin.jar
下载地址http://www.mysql.com/products/connector/
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE hibernate-configuration PUBLIC
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5 <hibernate-configuration>
6 <session-factory>
7
8 <!-- 配置连接数据库的基本信息 -->
9 <property name="connection.username">数据库用户名</property>
10 <property name="connection.password">数据库密码</property>
11 <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
12 <property name="connection.url">jdbc:mysql://localhost:3306/数据库名</property>
13
14 <!-- 配置Hibernate基本信息 -->
15 <!-- Hibernate所使用得数据库方言 -->
16 <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
17
18 <!-- 执行操作时是否在控制台打印sql -->
19 <property name="show_sql">true</property>
20
21 <!-- 是否对sql进行格式化 -->
22 <property name="format_sql">true</property>
23
24 <!-- 指定自动生成数据表的策略 -->
25 <property name="hbm2ddl.auto">update</property>
26
27 <!-- 指定关联的.hbm.xml文件 -->
28 <mapping resource="com/biubiu/domain/UserInfo.hbm.xml"/>
29 <mapping class="com.biubiu.domain.UserInfo"/>
30
31 </session-factory>
32 </hibernate-configuration>
最后写一个测试类,测试方法为:
1 @Test
2 public void test() {
3 //1.创建一个SessionFactory对象
4 SessionFactory seFactory = null;
5 final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
6 .configure() // configures settings from hibernate.cfg.xml
7 .build();
8 try{
9 seFactory = new MetadataSources( registry ).buildMetadata()
10 .buildSessionFactory();
11 } catch(Exception e){
12 StandardServiceRegistryBuilder.destroy( registry );
13 }
14
15
16 //2.创建一个Session对象
17
18 Session session = seFactory.openSession();
19
20 //3.开启事务
21 session.beginTransaction();
22 //4.执行操作
23
24 session.save(new UserInfo("[email protected]","测试",
25 "icuicu","0","img","tianmao"));
26
27 /*
28 //!!!!写hql语句,from 类名(区分大小写)
29 String hql = "from UserInfo";
30 @SuppressWarnings("unchecked")
31 List<UserInfo> list = session.createQuery(hql).list();
32 for(UserInfo u : list){
33 System.out.println(u);
34 }
35 */
36 //5.提交事务
37 session.getTransaction().commit();
38 //6.关闭Session
39 session.close();
40 //7.关闭SessionFactory
41 seFactory.close();
42
43 }
一个是存数据,另外一个是取数据,注意注释起来了
小LUA
面对敌人的严刑逼供,我一个字也没说,而是一五一十写了下来。