1、环境:

Maven :3.1.1

开发工具:Spring Tool Suite

数据库 : Mysql  5.6

2、项目文件结构

文件代码:

2.1 、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>hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>hibernate</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

 2.2 、HibernateUtil.java

package com.rhythmk.hibernate01;

import javax.imageio.spi.ServiceRegistry;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder; /*
* 参考 URL:
* http://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html_single/
* */
public class HibernateUtil {
// By : rhythmk.cnblogs.com
private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try { Configuration configuration=new Configuration().configure(); return configuration.buildSessionFactory(new ServiceRegistryBuilder().applySettings(configuration.getProperties()).build()); }
catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
} } public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

  

2.3、hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/shishuocms</property>
<property name="connection.username">root</property>
<property name="connection.password">wangkun</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property>
<!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于差错,程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后可以设置为false,提高运行效率 -->
<property name="hibernate.show_sql">true </property>
<mapping resource="com/rhythmk/model/user.hbm.xml" />
</session-factory> </hibernate-configuration>

2.4 User.java

package com.rhythmk.model;

import java.util.Date;

public class User {
public Integer getUserId() {
return userId;
} public void setUserId(Integer userId) {
this.userId = userId;
} public Integer getOpenId() {
return openId;
} public void setOpenId(Integer openId) {
this.openId = openId;
} @Override
public String toString() { return "User [userId=" + userId + ", openId=" + openId + ", type="
+ type + ", name=" + name + ", createTime=" + createTime + "]";
} public String getType() {
return type;
} public void setType(String type) {
this.type = type;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public Integer userId;
public Integer openId;
public String type;
public String name;
public Date createTime;
}

  2.5  user.hbm.xml

<?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>
<class name="com.rhythmk.model.User" table="user">
<id name="userId" type="int">
<column name="userId" />
<generator class="native" />
</id>
<property name="openId" type="int">
<column name="openId" not-null="true" />
</property>
<property name="type" type="string">
<column name="type" not-null="true" />
</property>
<property name="name" type="string">
<column name="name" length="45" not-null="true" />
</property>
<property name="createTime" type="timestamp">
<column name="createTime" not-null="true" />
</property> </class>
</hibernate-mapping>

3、测试代码(hibernatedemo1.java):

 插入:

@Test
public void InsertUser() { SessionFactory sessionfac = HibernateUtil.getSessionFactory(); Session session = null;
org.hibernate.Transaction tran = null;
try {
sessionfac.openSession();
User entity = new User();
tran = session.beginTransaction();
entity.setType("管理员");
entity.setName("rhythmk");
entity.setOpenId(1);
entity.setCreateTime(new Date());
session.save(entity);
tran.commit(); System.out.println("Insert into OK!");
} catch (Exception e) {
if (tran != null) {
tran.rollback();
}
e.printStackTrace();
} finally {
if (session != null)
session.close(); } }

  修改:

	@Test
public void UpdateUser() {
Session session = null;
org.hibernate.Transaction tran = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tran = session.beginTransaction();
User entity = (User) session.load(User.class, 2);
entity.setName("Update");
session.save(entity);
tran.commit(); entity = (User) session.load(User.class, 2); System.out.println(entity.toString()); } catch (Exception e) {
if (tran != null) {
tran.rollback();
}
// TODO: handle exception
e.printStackTrace(); } finally {
if (session != null)
session.close(); }
}

  删除:

@Test
public void DelUser() { Session session = null;
org.hibernate.Transaction tran = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tran = session.beginTransaction();
Object obj = session.load(User.class, 4);
User entity = null;
if (obj != null) {
entity = (User) obj;
} if (entity != null) {
session.delete(entity);
System.out.println("删除成功!");
tran.commit();
} } catch (Exception e) {
if (tran != null) {
tran.rollback();
}
// TODO: handle exception
e.printStackTrace(); } finally {
if (session != null)
session.close(); } }

  单对象查询

@Test
public void SelectUser() {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
User entity = (User) session.load(User.class, 2);
System.out.println(entity.toString()); } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (session != null)
session.close(); } }

 List查询

  

@Test
public void SelectListUser() {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
Query query= session.createQuery("from User ");
List<User> list=(List<User>)query.list();
for (User user : list) {
System.out.println(user);
} } catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null)
session.close(); }
}

  分页查询:

	@Test
public void SelectPageListUser() {
// 获取分页数据
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
Query query= session.createQuery("from User ");
List<User> list=(List<User>)query
.setFirstResult(0) //从0项开始
.setMaxResults(3) //每页三条数据
.list();
for (User user : list) {
System.out.println(user);
} } catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null)
session.close(); }
}

  代码包:http://pan.baidu.com/s/1hq1esh2

备注:

添加 JBOOS TOOL路径
http://download.jboss.org/jbosstools/updates/stable/helios/

Rhythmk 学习 Hibernate 01 - maven 创建Hibernate 项目之 增删改查入门的更多相关文章

  1. Mysql学习笔记(三)对表数据的增删改查。

    正文内容. 这一部分是最简单的,也是最麻烦的.简单是因为其实只包括增删该插四个部分.大体上看,增加数据.删除数据.修改数据.查询数据都不麻烦啊,我们日常都是常用的.这个谁不会呢?以前在培训机构学mys ...

  2. 使用MVC5+Entity Framework6的Code First模式创建数据库并实现增删改查功能

    此处采用VS2017+SqlServer数据库 一.创建项目并引用dll: 1.创建一个MVC项目 2.采用Nuget安装EF6.1.3 二.创建Model 在models文件夹中,建立相应的mode ...

  3. BitAdminCore框架应用篇:(二)创建一个简单的增删改查模块

    NET Core应用框架之BitAdminCore框架应用篇系列 框架演示:http://bit.bitdao.cn 框架源码:https://github.com/chenyinxin/cookie ...

  4. 数据库开发基础-SQl Server 控制数据库的服务+数据库的创建与管理(增删改查)

    控制数据库的服务: 方法一: 1.Windows+R 打开运行  打开cmd 2.输入net start MSSQLserver 启动数据库服务 输入net stop MSSQLserver 关闭数据 ...

  5. 数据库开发基础-★SQl Server 控制数据库的服务+数据库的创建与管理(增删改查)★

    控制数据库的服务: 方法一: 1.Windows+R 打开运行  打开cmd 2.输入net start MSSQLserver 启动数据库服务 输入net stop MSSQLserver 关闭数据 ...

  6. 【黑马Android】(04)数据库的创建和sql语句增删改查/LinearLayout展示列表数据/ListView的使用和BaseAdater/内容提供者创建

    数据库的创建和sql语句增删改查 1. 载入驱动. 2. 连接数据库. 3. 操作数据库. 创建表: create table person( _id integer primary key, nam ...

  7. Hibernate第一个程序(最基础的增删改查) --Hibernate

    本例实现Hibernate的第一个程序,Hibernate的优点我想大家都很清楚,在这里不做过多赘述.总之,使用Hibernate对数据库操作,也就是来操作实体对象的! 项目目录: 一.第一步要做的就 ...

  8. hibernate 一对多 多对一 关系表 增删改查大礼包ps二级查也有

    今天来到混元气功 这货大概的意思就是你中有我 我中有你 ps 这里就要说到维护关系 ps写这个用了我一下午.......也是刚刚好复习到这里 顺便就写写 注意:一般都在多方维护关系,至于是用单向还是用 ...

  9. 用泛型创建SqlServerHelper类实现增删改查(一)

    使用泛型,可以构建对数据库单表的基本增删改查. 首先有一数据库 Test_SqlServerHelper ,有2表 接下来创建项目,对数据库进行增删改查. 直接贴代码:(SqlServerHelper ...

随机推荐

  1. 微信小程序引入md5.js

    今天给大家安利一下微信小程序引入md5.js的方法,不多说 md5.js在下面 直接复制到项目的utils/md5.js即可 /* * A JavaScript implementation of t ...

  2. css样式中position和_position的区别

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA3IAAAEUCAIAAADhh5PYAAAgAElEQVR4nO3dPa/rNoLGcX6dW6UL+B ...

  3. IOS-网络(大文件下载)

    一.不合理方式 // // ViewController.m // IOS_0131_大文件下载 // // Created by ma c on 16/1/31. // Copyright © 20 ...

  4. 时间序列挖掘-预测算法-三次指数平滑法(Holt-Winters)——三次指数平滑算法可以很好的保存时间序列数据的趋势和季节性信息

    from:http://www.cnblogs.com/kemaswill/archive/2013/04/01/2993583.html 在时间序列中,我们需要基于该时间序列当前已有的数据来预测其在 ...

  5. Linux 需要掌握的一些命令

    详情: 1. tar 创建一个新的tar文件 $ tar cvf archive_name.tar dirname/ 解压tar文件 $ tar xvf archive_name.tar 查看tar文 ...

  6. Hive教程之metastore的三种模式

    Hive中metastore(元数据存储)的三种方式: 内嵌Derby方式 Local方式 Remote方式 [一].内嵌Derby方式 这个是Hive默认的启动模式,一般用于单元测试,这种存储方式有 ...

  7. Ext.js高级组件

    第二章:Ext.js高级组件 grid组件 普通方式 表格面板类Ext.grid.Panel xtype(别名):gridpanel.grid title标题.renderTo渲染至.width宽.h ...

  8. FastAdmin 开发第四天:初试命令行

    FastAdmin 最强大的是命令行 先从 test 表开始. 在 FastAdmin 默认有一个 test 表格,用于命令行 crud 测试. 如何开始? 只需要在项目命令行中输入以下命令就会自动生 ...

  9. Spring Could与Dubbo、Docker、K8S

    如果你是在一个中小型项目中应用Spring Cloud,那么你不需要太多的改造和适配,就可以实现微服务的基本功能.但是如果是在大型项目中实践微服务,可能会发现需要处理的问题还是比较多,尤其是项目中老代 ...

  10. Mplayer1.0rc2移植到am335x开发板

    因项目需要媒体播放器,所以准备使用QT+Mplayer来做,但遇到了屏幕闪烁的问题,无法满足需求. 1.参考<mplayer 移植到 arm 心得> ,http://blog.csdn.n ...