首页 > 其他分享 >hibernate_demo

hibernate_demo

时间:2023-08-21 23:44:35浏览次数:43  
标签:xml hibernate String demo mysql org public

参考:ORM----hibernate入门Demo(无敌详细版) - Old-凯 - 博客园 (cnblogs.com)

Hibernate - 基础入门详解_51CTO博客_hibernate入门

hmb.xml:Hibernate框架之hbm.xml映射文件(详解)_hibernate映射文件详解_hestyle的博客-CSDN博客

 

新建testdb数据库,创建tb_users表:

 模块整体目录结构:

 

pom.xml最初只添加了hibernate、mysql的依赖,其他jar包依赖是根据运行报错,一点点加上的。mysql依赖的版本要对应安装的mysql版本

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
    <artifactId>hibernate_demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <hibernate.version>5.2.10.Final</hibernate.version>
        <hibernate.validator.version>5.4.0.Final</hibernate.validator.version>
        <mysql.driver.version>8.0.21</mysql.driver.version>
    </properties>

    <dependencies>
        <!-- Hibernate包 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate.validator.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.driver.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-rt</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

  

User.java

package com.hmb;

public class User {
    public User() {
    }

    public User(Integer id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    private Integer id;
    private String name;
    private String pwd;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

  

User.hmb.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">
<hibernate-mapping>
    <class name="com.hmb.User" table="tb_users">
        <id name="id" column="userid">
            <generator class="native"></generator>            
        </id>
        <property name="name" column="name" type="string"/>
        <property name="pwd" column="pwd" type="string"/>
    </class>
</hibernate-mapping>

 

 hibernate.cfg.xml要放在resources目录下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connect.driver_class">com.mysql.jdbc.Driver</property>
        <!--testdb为数据库名-->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
<!--        填登录数据库的账号、密码-->
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">******</property>
        <property name="format_sql">true</property>
        <mapping resource="com/hmb/User.hmb.xml"/>
    </session-factory>
</hibernate-configuration>

  

Main.java

package com.hmb;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class Main {
    public static void main(String[] args) {
        Configuration config = new Configuration().configure("hibernate.cfg.xml");
        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.openSession();
        Transaction transaction = session.beginTransaction();

        User user = new User(3, "wangwu", "123456");
        session.save(user);
        transaction.commit();
        session.clear();
        factory.close();
    }
}

运行效果:

 查看数据表成功新增了数据

 其他:

运行时如果报错”java.lang.NoSuchMethodException: sun.misc.Unsafe.defineClass(java.lang.String“,可添加jvm启动参数”--add-opens java.base/java.lang=ALL-UNNAMED“:

 

标签:xml,hibernate,String,demo,mysql,org,public
From: https://www.cnblogs.com/hemeiwolong/p/17626995.html

相关文章

  • OpenTiny Vue 3.10.0 版本发布:组件 Demo 支持 Composition 写法,新增4个新组件
    我们非常高兴地宣布,2023年8月14日,OpenTinyVue发布了v3.10.0 ......
  • FastApi-1-结合sql 增/查demo
    目录FastAPI学习记录项目结构部分接口/代码展示感受全部代码FastAPI学习记录fastapi已经学习有一段时间,今天抽时间简单整理下。官网介绍:FastAPI是一个用于构建API的现代、快速(高性能)的web框架,使用Python3.6+并基于标准的Python类型提示。快速:可与NodeJS和Go......
  • Hibernate文字与格式化字符串不匹配错误
    今天这个呢,主要是在使用Hibernate的时候遇到过这个问题,想着别人可能也会遇到这个问题,那么就简单的来记录一下问题的产生以及解决方案。事情的起因是做一个需求,然后测试反馈说这个有个功能报错阻断流程了,让抽时间排查一下,我一开始以为是数据问题,后来我自己环境上尝试了一下,也的确......
  • tk的一个布局demo
    效果代码importtkinterastkfromtkinterimportscrolledtextimportrequestsdefQ_A(data):headers={'origin':'https://chat2.jinshutuan.com','referer':'https://chat2.jinshutuan.com/&......
  • python监控redis demo
    下载aioredis为了提升性能我们使用一部redispipinstallaioredisdemo:importasyncioimportaioredis#每隔10s获取redis信息asyncdefmonitor_redis(host,port,interval):#建立异步Redis连接redis_uri=f"redis://{host}:{port}"redis=awaitai......
  • 错误org.hibernate.AnnotationException: No identifier specified for entity
    AnnotationExceptionNoidentifierspecifiedforentity错误org.hibernate.AnnotationException:Noidentifierspecifiedforentityorg.hibernate.AnnotationException:Noidentifierspecifiedforentity.报这个异常的原因是因为JavaBean的主键没有注解映射关系,加上对应......
  • hibernate二级缓存
     (一)什么样的数据适合存放到第二级缓存中?1很少被修改的数据2不是很重要的数据,允许出现偶尔并发的数据3不会被并发访问的数据4参考数据,指的是供应用参考的常量数据,它的实例数目有限,它的实例会被许多其他类的实例引用,实例极少或者从来不会被修改。(二)不适合存放到第二级缓存的数......
  • spring配合hibernate报错:sessionFactory or hibernateTemplate is required
    Causedby:java.lang.IllegalArgumentException:'sessionFactory'or'hibernateTemplate'isrequired atorg.springframework.orm.hibernate3.support.HibernateDaoSupport.checkDaoConfig(HibernateDaoSupport.java:118) atorg.springframework.......
  • 适老化demo
    --------------------------------------------------------html------------------------------------------------------<!doctypehtml><htmllang="en"> <head> <metacharset="UTF-8"> <title>鼠标移入视频播放,鼠标移出播放停止,恢......
  • 关于Mybatis 和 Hibernate 持久层框架之间的区别
    首先,Mybatis和Hibernate都是ORM持久层框架不同点在于,MyBatis是半自动的,它需要开发人员自己手动编写SQL语句。一、MybatisMyBatis支持通过XML或注解的方式来配置需要运行的SQL语句,并且,最终由框架本身将Java对象和SQL语句映射生成最终执行的SQL,执行后,再将结果映射......