Hibernate常用的Java数据类型映射到mysql和Oracle

  研究了常用的Java基本数据类型在mysql和oracle数据库的映射类型。这里使用的是包装类型做研究,一般在hibernate声明的时候最好不要用基本类型,因为数据库中的null空数据有可能映射为基本类型的时候会报错,但是映射到包装类型的时候值为null,不会报错。

1.常见数据类型在Mysql数据库的映射

实体:

package cn.qlq.domain;import java.sql.Time;
import java.util.Date;public class TestType {private Long id;private Integer age;private Character sex;private Boolean isPerson;private Date birth;private Time birthTime;private String name;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Character getSex() {return sex;}public void setSex(Character sex) {this.sex = sex;}public Boolean getIsPerson() {return isPerson;}public void setIsPerson(Boolean isPerson) {this.isPerson = isPerson;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Time getBirthTime() {return birthTime;}public void setBirthTime(Time birthTime) {this.birthTime = birthTime;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "TestType [id=" + id + ", age=" + age + ", sex=" + sex + ", isPerson=" + isPerson + ", birth=" + birth+ ", birthTime=" + birthTime + ", name=" + name + "]";}}

 

 

 

xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><!-- 配置表与实体对象的关系 --><!-- package属性:填写一个包名.在元素内部凡是需要书写完整类名的属性,可以直接写简答类名了. -->
<hibernate-mapping package="cn.qlq.domain" ><!-- class元素: 配置实体与表的对应关系的name: 完整类名table:数据库表名--><class name="TestType" table="testtype" ><!-- id元素:配置主键映射的属性name: 填写主键对应属性名column(可选): 填写表中的主键列名.默认值:列名会默认使用属性名type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.每个类型有三种填法: java类型|hibernate类型|数据库类型not-null(可选):配置该属性(列)是否不能为空. 默认值:falselength(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度--><id name="id"  ><!-- generator:主键生成策略 --><!--identity : 主键自增.由数据库来维护主键值.录入时不需要指定主键.  --><generator class="native"></generator></id><!-- property元素:除id之外的普通属性映射name: 填写属性名column(可选): 填写列名type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.每个类型有三种填法: java类型|hibernate类型|数据库类型not-null(可选):配置该属性(列)是否不能为空. 默认值:falselength(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度--><property name="age"/><property name="sex"/><property name="isPerson"/><property name="birth"/><property name="birthTime"/><property name="name"/></class>
</hibernate-mapping>

 

 

Mysql映射的类型:

mysql> desc testtype;
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| age       | int(11)      | YES  |     | NULL    |                |
| sex       | char(1)      | YES  |     | NULL    |                |
| isPerson  | bit(1)       | YES  |     | NULL    |                |
| birth     | datetime     | YES  |     | NULL    |                |
| birthTime | time         | YES  |     | NULL    |                |
| name      | varchar(255) | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
7 rows in set (0.01 sec)

 

 

结果:

Long------------------------------bigint

Integer-----------------------    int

Character---------------------  char

Bolean---------------------------bit

java.util.Date;--------------datetime

java.sql.Time;------------------time

String----------------------------varchar(255)

 

  • 插入数据:
    public static void main(String[] args) {//3.3以及之前的版本构建会话工厂对象
//        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();//5.0之后获取SessionFactory//创建服务注册对象ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();//创建会话工厂对象SessionFactory  sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();//获取session对象Session session = sessionFactory.openSession();//开启事务Transaction tx = session.beginTransaction();//保存对象TestType t1 = new TestType();TestType t2 = new TestType();t1.setAge(22);t2.setAge(23);t1.setName("zhangsan");t2.setName("zhangsanhaha");t1.setSex('1');t2.setSex('2');t1.setBirth(new Date());t2.setBirth(new Date());t1.setIsPerson(true);t2.setIsPerson(false);session.save(t1);session.save(t2);tx.commit();//关闭流
        session.close();sessionFactory.close();}

 

 

结果:

mysql> select * from testtype;
+----+------+------+----------+---------------------+-----------+--------------+
| id | age  | sex  | isPerson | birth               | birthTime | name         |
+----+------+------+----------+---------------------+-----------+--------------+
|  1 |   22 | 1    |         | 2018-08-10 22:39:19 | NULL      | zhangsan     |
|  2 |   23 | 2    |          | 2018-08-10 22:39:19 | NULL      | zhangsanhaha |
+----+------+------+----------+---------------------+-----------+--------------+
2 rows in set (0.00 sec)

 

 

 

  • 查询

(1)基本查询:

    @Test// HQL查询所有数据public void fun1() {// 1 获得sessionSession session = HibernateUtil.openSession();// 2.书写HQL语句
//        String hql = "from cn.qlq.domain.Customer";// from 类名全路径String hql = "from TestType";// 如果整个项目中只有这一个类名可以直接写名字// 3.根据hql创建查询对象Query query = session.createQuery(hql);// 4.根据查询对象获取查询结果List<TestType> list = query.list();System.out.println(list);}

 

结果:

[TestType [id=1, age=22, sex=1, isPerson=true, birth=2018-08-10 22:39:19.0, birthTime=null, name=zhangsan], TestType [id=2, age=23, sex=2, isPerson=false, birth=2018-08-10 22:39:19.0, birthTime=null, name=zhangsanhaha]]

 

(2)条件查询:----针对上面的类型进行条件查询

    @Test// HQL查询所有数据public void fun1() {// 1 获得sessionSession session = HibernateUtil.openSession();// 2.书写HQL语句
//        String hql = "from cn.qlq.domain.Customer";// from 类名全路径String hql = "from TestType where age = 22 and sex = 1 and isPerson = true and name = 'zhangsan' and birth like '2018-08-10%'";// 如果整个项目中只有这一个类名可以直接写名字// 3.根据hql创建查询对象Query query = session.createQuery(hql);// 4.根据查询对象获取查询结果List<TestType> list = query.list();System.out.println(list);}

 

 

结果:

    selecttesttype0_.id as id1_0_,testtype0_.age as age2_0_,testtype0_.sex as sex3_0_,testtype0_.isPerson as isPerson4_0_,testtype0_.birth as birth5_0_,testtype0_.birthTime as birthTim6_0_,testtype0_.name as name7_0_ fromtesttype testtype0_ wheretesttype0_.age=22 and testtype0_.sex=1 and testtype0_.isPerson=1 and testtype0_.name='zhangsan' and (testtype0_.birth like '2018-08-10%')
[TestType [id=1, age=22, sex=1, isPerson=true, birth=2018-08-10 22:39:19.0, birthTime=null, name=zhangsan]]

 

 

补充:Mysql的boolean类型也可以用true_false表示,数据类型会变为char(1),存的是T和F:

     <property name="isPerson" type="true_false"/>

 

 

2.常见数据类型在Oracle数据库的映射

Oracle映射上面直接映射会报错,解决办法:  将boolean映射为hibernate的true_false  (原理都是在数据库存T或者F,F为false,T为true)

第一种:   boolean映射为yes_no

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><!-- 配置表与实体对象的关系 --><!-- package属性:填写一个包名.在元素内部凡是需要书写完整类名的属性,可以直接写简答类名了. -->
<hibernate-mapping package="cn.qlq.domain" ><!-- class元素: 配置实体与表的对应关系的name: 完整类名table:数据库表名--><class name="TestType" table="testtype" ><!-- id元素:配置主键映射的属性name: 填写主键对应属性名column(可选): 填写表中的主键列名.默认值:列名会默认使用属性名type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.每个类型有三种填法: java类型|hibernate类型|数据库类型not-null(可选):配置该属性(列)是否不能为空. 默认值:falselength(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度--><id name="id"  ><!-- generator:主键生成策略 --><!--identity : 主键自增.由数据库来维护主键值.录入时不需要指定主键.  --><generator class="native"></generator></id><!-- property元素:除id之外的普通属性映射name: 填写属性名column(可选): 填写列名type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.每个类型有三种填法: java类型|hibernate类型|数据库类型not-null(可选):配置该属性(列)是否不能为空. 默认值:falselength(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度--><property name="age"/><property name="sex"/>  <property name="isPerson" type="true_false"/><property name="birth"/><property name="birthTime"/><property name="name"/></class>
</hibernate-mapping>

 

 

结果:

 

 

总结:

Long------------------------------number

Integer-----------------------    number

Character---------------------  char

Bolean---------------------------char

java.util.Date;--------------date

java.sql.Time;------------------date

String----------------------------varchar(255)

 

 

添加数据:

package cn.qlq.util;import java.util.Date;import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;import cn.qlq.domain.TestType;public class TestSave {public static void main(String[] args) {//3.3以及之前的版本构建会话工厂对象
//        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();//5.0之后获取SessionFactory//创建服务注册对象ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();//创建会话工厂对象SessionFactory  sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();//获取session对象Session session = sessionFactory.openSession();//开启事务Transaction tx = session.beginTransaction();//保存对象TestType t1 = new TestType();TestType t2 = new TestType();t1.setAge(22);t2.setAge(23);t1.setName("zhangsan");t2.setName("zhangsanhaha");t1.setSex('1');t2.setSex('2');t1.setBirth(new Date());t2.setBirth(new Date());t1.setIsPerson(true);t2.setIsPerson(false);session.save(t1);session.save(t2);tx.commit();//关闭流
        session.close();sessionFactory.close();} }

 

结果:

 

 

 

  • 查询所有:
    @Test// HQL查询所有数据public void fun1() {// 1 获得sessionSession session = HibernateUtil.openSession();// 2.书写HQL语句String hql = "from cn.qlq.domain.TestType";// from 类名全路径// 3.根据hql创建查询对象Query query = session.createQuery(hql);// 4.根据查询对象获取查询结果List<TestType> list = query.list();System.out.println(list);}

 

结果:

Hibernate: selecttesttype0_.id as id1_0_,testtype0_.age as age2_0_,testtype0_.sex as sex3_0_,testtype0_.isPerson as isPerson4_0_,testtype0_.birth as birth5_0_,testtype0_.birthTime as birthTim6_0_,testtype0_.name as name7_0_ fromtesttype testtype0_
[TestType [id=15, age=22, sex=1, isPerson=true, birth=2018-08-10 23:19:33.0, birthTime=null, name=zhangsan], TestType [id=16, age=23, sex=2, isPerson=false, birth=2018-08-10 23:19:33.0, birthTime=null, name=zhangsanhaha]]

 

 

 

 

 

  •  按上面的条件查询:
    @Test// HQL查询所有数据public void fun1() {// 1 获得sessionSession session = HibernateUtil.openSession();// 2.书写HQL语句String hql = "from TestType where age = 22 and sex = 1 and isPerson = true and name = 'zhangsan'";// 如果整个项目中只有这一个类名可以直接写名字// 3.根据hql创建查询对象Query query = session.createQuery(hql);// 4.根据查询对象获取查询结果List<TestType> list = query.list();System.out.println(list);}

 

结果:  (日期不能直接like了)

Hibernate: selecttesttype0_.id as id1_0_,testtype0_.age as age2_0_,testtype0_.sex as sex3_0_,testtype0_.isPerson as isPerson4_0_,testtype0_.birth as birth5_0_,testtype0_.birthTime as birthTim6_0_,testtype0_.name as name7_0_ fromtesttype testtype0_ wheretesttype0_.age=22 and testtype0_.sex=1 and testtype0_.isPerson='T' and testtype0_.name='zhangsan'
[TestType [id=15, age=22, sex=1, isPerson=true, birth=2018-08-10 23:19:33.0, birthTime=null, name=zhangsan]]

 

 

 总结: 

  对于mysql和oracle的boolean的通用类型就是true_false,hibernate会将字段类型设置为char(1),然后true的时候存T,false的时候存F。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/qlqwjy/p/9457988.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/570553.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Spring Cloud 之 Feign 使用HTTP请求远程服务

Feign是从Netflix中分离出来的轻量级项目&#xff0c;能够在类接口上添加注释&#xff0c;成为一个REST API 客户端&#xff0c;Feign默认集成了Ribbon。 Feign中对 Hystrix 有依赖关系。Feign只是一个便利的rest框架&#xff0c;简化调用&#xff0c;最后还是通过ribbon在注册…

UI控件之UISlider

一、创建 UISlider *slider [[UISlider alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width-100, 50)]; 二、设置最大最小值 slider.minimumValue 0; slider.maximumValue 1; 三、改变圆形前面和后面的颜色 slider.minimumTrackTintColor [UIColor orang…

Front End Accessibility Development Guide

Header Carefully write heading(h1,h2,h3) for screen reader. Alternative Image Provide alt text for both essential and functional images. Provide empty alt text (alt””) for decorative images. Don’t repeat the alt text of an image in the adjacent text. De…

详细的Windows下安装 binwalk

1. https://github.com/ReFirmLabs/binwalk到这里下载binwalk&#xff0c;下载后解压。 2. 找到下载后的文件夹&#xff0c; 在这里要进行安装步骤&#xff0c;一边按着shift&#xff0c;一边按着鼠标右键&#xff0c;点击在此处打开命令窗口。 输入python setup.py install 安…

各大浏览器清除缓存(cache)详细步骤

1. Firefox 1.1 选择“Options”&#xff1a; 1.2 选择“Advanced”->“Network”->“Cached Web Content”&#xff0c;点击“Clear Now”&#xff1a; 2. Chrome 2.1 选择“Settings”&#xff1a; 2.2 点击页面底部“Show advanced settings”&#xff1a; 2.3 选择…

python部分 + 数据库 + 网络编程

PS:附上我的博客地址&#xff0c;答案中略的部分我的博客都有&#xff0c;直接原标题搜索即可。https://www.cnblogs.com/Roc-Atlantis/第一部分 Python基础篇&#xff08;80题&#xff09;为什么学习Python&#xff1f;Omit通过什么途径学习的Python&#xff1f;OmitPython和J…

使用 angular directive 和 json 数据的 D3 带标签 donut chart示例

利用angular resource加载priorityData.json中的json数据&#xff0c;结合D3画出甜甜圈图。运行index.html结果如图所示&#xff1a; priorityData.json中json数据如下&#xff1a; { "priority":{ "Blocker":12,"Critical":18,"Major&qu…

第一个express app 详细步骤

1. 全局安装node.js&#xff08;请参考网上教程&#xff09;。 如何判断是否全局安装成功&#xff1f;打开命令行终端&#xff0c;进入任意文件夹&#xff0c;输入node&#xff0c;不报错。 2. 安装express 2.1 创建app文件夹。并在此文件夹下创建文件package.json如下&#…

【scarletthln 关于算法的一点总结】

1. 分解问题的角度: fix 某一维度&#xff0c;尝试另一维度上的所有可能 a. 可能是array的(i, j)pointers, b. 可能是矩形的长与宽, c. 可能是tree的每一个subtree, d. 可能是情景题的每一对pair...2. 求所有解的, 暴力上backtracking吧3. 如果问最短/最少的, 先想BFS、DP这对…

Angularjs Nodejs Grunt 一个例子

做了一个简单的示例&#xff0c;目的是记录环境配置以及这套框架的结构流程。 1.配置环境 默认nodejs已安装。 安装以下模块&#xff1a;express&#xff08;nodejs框架&#xff09;,grunt&#xff08;javascript task runner&#xff09;,grunt-contrib-watch&#xff08;g…

【C#/WPF】用Thumb做可拖拽的UI控件

【C#/WPF】用Thumb做可拖拽的UI控件 原文:【C#/WPF】用Thumb做可拖拽的UI控件需求&#xff1a;简单的可拖拽的图片 使用System.Windows.Controls.Primitives.Thumb类 前台&#xff1a; <Canvas x:Name"g"><Thumb Canvas.Left"10" Canvas.Top"…

PHP 常用设计模式 (转载)

1.单例模式 单例模式顾名思义&#xff0c;就是只有一个实例。作为对象的创建模式&#xff0c; 单例模式确保某一个类只有一个实例&#xff0c;而且自行实例化并向整个系统提供这个实例。 单例模式的要点有三个&#xff1a; 一是某个类只能有一个实例&#xff1b;二是它必须自行…

Angularjs切换网站配色模式简单示例1(切换css文件)

一个网站可以有多种配色方案&#xff0c;例如正常模式&#xff0c;夜间模式等。 简单示例一个通过点击按钮&#xff0c;更换css文件&#xff0c;达到切换配色模式的angularjs 小app。 主要文件有三个&#xff1a;index.html&#xff08;主文件&#xff09;&#xff0c;white.…

【转】在树莓派上实现人脸识别

教程参考地址&#xff1a;http://shumeipai.nxez.com/2018/08/12/facial-recognition-identification-on-raspberry-pi.html 转载于:https://www.cnblogs.com/little-kwy/p/9481259.html

Angularjs切换网站配色模式简单示例2(切换body元素的class)

一个网站可以有多种配色方案&#xff0c;例如正常模式&#xff0c;夜间模式等。 简单示例一个通过点击toggle 按钮&#xff0c;切换body元素的class&#xff0c;达到切换配色模式的angularjs小app。 1. Live范例可以在以下Codepen网址查看&#xff1a; http://codepen.io/Chris…

Eclipse中Maven项目出现红色感叹号问题

在Eclipse环境下&#xff0c;有时我们会遇到Maven项目出现红色感叹号的情形&#xff0c;而一旦项目出现感叹号&#xff0c;Eclipse便无法帮我们进行自动编译等工作&#xff0c;尽管有时候不会影响运行&#xff0c;但每次只能手动启动Maven重新编译&#xff0c;非常不便&#xf…

GitHub 配置及简单使用

一. 初始化 1. 初始化 git 目录 终端中进入到项目文件夹&#xff0c;然后输入以下命令。 git init 命令执行后&#xff0c;文件夹中会多一个.git 文件夹 2. 设置本机关联 GItHub 的用户名和邮箱 git config --global user.name "<username>" git conf…

斐波那契数列 (C#)

斐波那契数列&#xff08;Fibonacci sequence&#xff09;&#xff0c;又称黄金分割数列、因数学家列昂纳多斐波那契&#xff08;Leonardoda Fibonacci&#xff09;以兔子繁殖为例子而引入&#xff0c;故又称为“兔子数列”&#xff0c;指的是这样一个数列&#xff1a;1、1、2、…

Javascript 处理 JSON 数据 示例

最近做了一个 MEAN stack 的 app 。后台用 NodeJS 从 Jira rest api 获得JSON数据并做处理&#xff0c;然后前端用 AngularJS Ajax call 获得处理后的 JSON 数据&#xff0c;显示到 App 上。处理了很多 JSON 数据&#xff0c;决定编一个例子&#xff0c;写一个总结。 JSON 数据…

ansible常用命令

一、ansible常用命令 一、ansible命令的常用参数 ansible 默认提供了很多模块来供我们使用。在 Linux 中&#xff0c;我们可以通过 ansible-doc -l 命令查看到当前 ansible 都支持哪些模块&#xff0c;通过 ansible-doc -s 模块名 又可以查看该模块有哪些参数可以使用。 1、…