从零开始用hibernate连接并操作数据库(1)

1. 新建项目

  1. 首先新建一个Hibernate的项目
    在这里插入图片描述

  2. 同时在新建的同时要导入Hibernate要用的lib包
    在这里插入图片描述





2. 添加数据库

  1. 添加本地的数据库
    在这里插入图片描述
  2. 测试连接数据库
    填上登录数据库的账户和密码
    然后点击下方的Test Connection来测试连接在这里插入图片描述
    这个时候极有可能会报错

Server returns invalid timezone. Need to set ‘serverTimezone’ property.




**解决办法:** 在Advanced中找到serverTimezone属性,将其中的UTC改成GMT

在这里插入图片描述
在这里插入图片描述






最后再回头测试

在这里插入图片描述






连接成功

在这里插入图片描述




3. 编写实体类

  1. 在src下新建任意一个包
    在这里插入图片描述

  2. 新建一个java文件写实体类(Customer.java)

    private Integer id;
    private String name;
    private Integer age;
    private String sex;
    private String city;
  1. 直接使用alt+insert键快速生成get、set以及tostring方法
    在这里插入图片描述
    代码如下:
package cn.itcast.domain;

public class Customer {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
    private String city;

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Customer[" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", city='" + city + '\'' +
                ']';
    }
}

  1. 编写映射文件Customer.hbm.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="cn.itcast.domain.Customer" table="customer">
        <!--主码-->
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <!--其他码-->
        <property name="name" column="name" type="string"/>
        <property name="age" column="age" type="integer"/>
        <property name="sex" column="sex" type="string"/>
        <property name="city" column="city" type="string"/>
    </class>
</hibernate-mapping>



4. 编写核心配置文件

基本上可以说是套用个标准化模板就好了

重点注意:
连接数据库的url:jdbc:mysql://localhost:3306/数据库名

<?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.connection.driver_class">
	    com.mysql.jdbc.Driver
	</property>
    <!--连接数据库的url -->
	<property name="hibernate.connection.url">
		jdbc:mysql://localhost:3306/chapter07
	</property>
	<!--数据库的用户名 -->
	<property name="hibernate.connection.username">
		root
	</property>
	<!--数据库的密码 -->
	<property name="hibernate.connection.password">
		root
	</property>	
	
	<!-- C3P0连接池设定 -->
	<!-- 使用c3po连接池 配置连接池提供的供应商 -->
	<property name="connection.provider_class">
	   org.hibernate.connection.C3P0ConnectionProvider
	</property>
	<!--在连接池中可用的数据库连接的最少数目 -->
	<property name="c3p0.min_size">5</property>
	<!--在连接池中所有数据库连接的最大数目 -->
	<property name="c3p0.max_size">20</property>
	<!--设定数据库连接的过期时间,以毫秒为单位, 
	如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,
	就会从连接池中清除 -->
	<property name="c3p0.timeout">120</property>
	<!--3000秒检查所有连接池中的空闲连接 以秒为单位 -->
	<property name="c3p0.idle_test_period">3000</property>
	
	
     <!--其它配置 -->
    <!-- 显示sql语句 -->
	<property name="hibernate.show_sql">true</property>
	<!-- 格式化sql语句 -->
	<property name="format_sql">true</property> 
    <!--自动建表 -->
	<property name="hibernate.hbm2ddl.auto">update</property> 

	<!-- 用来关联hbm配置文件 -->
	<mapping resource="cn/itcast/domain/Customer.hbm.xml"/>
 </session-factory>
</hibernate-configuration>	



5. 编写测试类测试连接

  1. 直接使用ctrl+shift+T快捷键新建test类
    在这里插入图片描述
  2. 新建完之后写代码到@Test时会报错
    会提示要导入包jubit,这个点下之后会要一点时间,但是没问题
  3. 写插入操作
	@Test
	public void insertTest() {
		// 1.加载hibernate.cfg.xml配置
		//Configuration config = new Configuration().configure("/config/hibernate.cfg.xml");//查找指定位置的配制文件
		Configuration config = new Configuration().configure();//默认去类路径的根目录下查找名称为hibernate.cfg.xml的文件
		// 2.获取SessionFactory
		SessionFactory sessionFactory = config.buildSessionFactory();
		// 3.得到一个Session
		Session session = sessionFactory.openSession();
		// 4.开启事务
		 Transaction t = session.beginTransaction();
		session.beginTransaction();
		// 5.操作
		// 5.1创建一个对象
		Customer c = new Customer();
		c.setName("王五");
		c.setAge(20);
		c.setCity("上海");
		c.setSex("男");
		// 5.2将数据存储到表中
		session.save(c);
		// 6.提交事务
		 t.commit();
		// 7.关闭资源
		session.close();
		sessionFactory.close();
	}
  1. 在运行的时候会出现一个警告,当然是不会影响结果的
    在这里插入图片描述
    要是想解决需要这个问题,那就在src目录下加入一个log4j.properties
    具体内容请参考其他博客,这个我不清楚参数什么意思
  2. 写完改查删
    完整代码
package cn.itcast.test;

import cn.itcast.domain.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;



public class CustomerTest {
    @Test
    public void insertTest(){
        //加载配置
        Configuration config = new Configuration().configure();

        SessionFactory sessionFactory = config.buildSessionFactory();
        Session session = sessionFactory.openSession();
        //开启事务
        Transaction t = session.beginTransaction();
        
        Customer c = new Customer();
        c.setName("王五");
        c.setAge(20);
        c.setCity("上海");
        c.setSex("男");

        //保存
        session.save(c);
        t.commit();
        session.close();
        sessionFactory.close();
    }

    @Test
    public void updateTest() {
        Configuration config = new Configuration().configure();
        SessionFactory sessionFactory = config.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();

        Customer c = new Customer();
        c.setId(5);
        c.setName("李四");
        c.setAge(20);
        c.setSex("男");
        c.setCity("广州");

        //更新
        session.update(c);
        t.commit();
        session.close();
        sessionFactory.close();
    }

    @Test
    public void findByIdTest() {
        Configuration config = new Configuration().configure();
        SessionFactory sessionFactory = config.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();

        //get查询(第二个参数为id编号)
        Customer c=(Customer) session.get(Customer.class, 4);
        System.out.println("姓名:"+c.getName());
        System.out.println("年龄:"+c.getAge());
        System.out.println("性别:"+c.getSex());
        System.out.println("所在城市:"+c.getCity());

        t.commit();
        session.close();
        sessionFactory.close();
    }

    @Test
    public void deleteByIdTest() {
        Configuration config = new Configuration().configure();
        SessionFactory sessionFactory = config.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();

        //先查询(第二个参数为id编号)
        Customer c = (Customer) session.get(Customer.class, 5);
        //再删除
        session.delete(c);

        t.commit();
        session.close();
        sessionFactory.close();
    }
}

6. 结果截图

在这里插入图片描述


2. 改

在这里插入图片描述


3. 查

在这里插入图片描述


4. 删

在这里插入图片描述





7. 结尾

测试过了那么可以封装一下,直接调用静态方法就可以了

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值