使用Maven创建Hibernate过程

使用Maven创建Hibernate过程

1.基本流程

我们先打开MYSQL,创建一个test的数据库,然后在该库下创建一个product_表

use test;
 
CREATE TABLE product_ (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(30) ,
  price float ,
  PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;

创建一个Maven项目,我们先在pom.xml文件下编写相关的配置,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>Maven14</name>
  <groupId>com.young</groupId>
  <artifactId>Maven14</artifactId>
  <version>1.0-SNAPSHOT</version>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.7</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8888</port>
              <maxIdleTime>30000</maxIdleTime>
            </connector>
          </connectors>
          <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
          <contextPath>/</contextPath>
        </configuration>
      </plugin>
    </plugins>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*hbm.xml</include>
        </includes>
      </resource>
    </resources>
  </build>

  <dependencies>
    <!--dependency>
      <groupId>com.young</groupId>
      <artifactId>[the artifact id of the block to be mounted]</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.27</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.3.2.Final</version>
    </dependency>
  </dependencies>

</project>

然后在main目录下的java目录下,创建一个包,假设命名为com.young.pojo,在这个包下创建一个Product类,代码如下:

package com.young.pojo;

public class Product {
    private int id;
    private String name;
    private float price;
    public int getId(){
        return id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setId(int id) {
        this.id = id;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
}

然后在java目录下再创建一个软件包,假设命名为com.young.test,在这个报下创建一个TestHibernate.java,用于测试,代码如下:

package com.young.test;

import com.young.pojo.Product;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class TestHibernate {
    public static void main(String[]args){
        //获取SessionFactory
        SessionFactory sf=new Configuration().configure().buildSessionFactory();
        //获取Session
        Session s=sf.openSession();
        //开启事务
        s.beginTransaction();
        Product p=new Product();
        p.setName("iphone7");
        p.setPrice(7000);
        //把对象保存到数据库
        s.save(p);
        //提交事务
        s.getTransaction().commit();
        s.close();
        sf.close();
    }
}

接着我们在resources目录下,创建Product.hbm.xml文件,用于映射Product类对应数据库中的product_表,代码如下:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.young.pojo">
    <class name="Product" table="product_">
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>
        <property name="name" />
        <property name="price" />
    </class>

</hibernate-mapping>

然后在resource目录下再创建一个hibernate.cfg.xml,配置访问数据库要用到的驱动,url,账号密码等,代码如下:

<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test?useSSL=false&amp;serverTimezone=UTC</property>
        <property name="connection.username">root</property>
        <property name="connection.password">mima</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping resource="Product.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

完整的目录结构如下图:
在这里插入图片描述
运行结果如下:
在这里插入图片描述
我们打开MySQL,查询product_表,结果如下
在这里插入图片描述
说明插入成功。
注意事项:如果运行后,出现错误,可以通过删除target文件并重新运行。
还有一点需要注意的是,Maven每次寻找资源时,都会在resource目录下寻找,所以我们那些和hibernate配置有关的xml文件,都有放在resource目录下

2.进行增删改查操作

我们向创建的product_表中添加一行数据
修改TestHibernate.java的main函数,代码如下:

 SessionFactory sf=new Configuration().configure().buildSessionFactory();
        Session s=sf.openSession();
        s.beginTransaction();
        for(int i=0;i<10;i++)
        {
          Product p=new Product();
           p.setName("iPhone"+i);
           p.setPrice(2000);
           s.save(p);
        }
        s.getTransaction().commit();
        s.close();
        sf.close();

获取id=5的产品名,代码如下:

 SessionFactory sf=new Configuration().configure().buildSessionFactory();
        Session s=sf.openSession();
        s.beginTransaction();
Product p=(Product)s.get(Product.class,6);
System.out.println("id=6的产品名称是:"+p.getName());
  s.getTransaction().commit();
        s.close();
        sf.close();

删除id=5的产品

SessionFactory sf=new Configuration().configure().buildSessionFactory();
        Session s=sf.openSession();
        s.beginTransaction();
       Product p=(Product)s.get(Product.class,5);
       s.delete(p);
        s.getTransaction().commit();
        s.close();
        sf.close();

修改id=6的产品

SessionFactory sf=new Configuration().configure().buildSessionFactory();
        Session s=sf.openSession();
        s.beginTransaction();
       Product p=(Product)s.get(Product.class,6);
System.out.println(p.getName());
p.setName("iphone-modified");
s.update(p);
      s.update(c);
        s.getTransaction().commit();
        s.close();
        sf.close();

通过hql语句获取产品名中带有iphone的产品

SessionFactory sf=new Configuration().configure().buildSessionFactory();
String name="iphone";
        Session s=sf.openSession();
        s.beginTransaction();
      Query q=s.createQuery("from Product p where p.name like ?1");
q.setParameter(1,"%"+name+"%");
List<Product>ps=q.list();
for(Product p:ps){
    System.out.println(p.getName());
}
        s.getTransaction().commit();
        s.close();
        sf.close();

使用Criteria进行查询

SessionFactory sf=new Configuration().configure().buildSessionFactory();
        Session s=sf.openSession();
        s.beginTransaction();
     String name="iphone";
Criteria c=s.createCriteria(Product.class);
c.add(Restrictions.like("name","%"+name+"%"));
List<Product>ps=c.list();
for(Product p:ps){
    System.out.println(p.getName());
}
        s.getTransaction().commit();
        s.close();
        sf.close();

3.分页查询

我们从第三行开始,查询5条数据,修改TestHibernate.java的main函数,代码如下:

//获取SessionF
 SessionFactory sf=new Configuration().configure().buildSessionFactory();
 //获取Session
        Session s=sf.openSession();
        //开启事务
        s.beginTransaction();
        String name="iphone";
        Criteria c=s.createCriteria(Product.class);
        c.add(Restrictions.like("name","%"+name+"%"));
        //表示从第3条数据开始
        c.setFirstResult(2);
        //表示查询5条数据
        c.setMaxResults(5);
        List<Product>ps=c.list();
        for(Product p:ps){
            System.out.println(p.getName());
        }
        //提交事务
        s.getTransaction().commit();
        s.close();
        sf.close();
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值