Hibernate4使用Annotation连接访问MySQL的小例子

1、创建一个Teacher类

package com.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Teacher {
	private int id;
	private String name;
	private String title;
	
@Id	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	
}

--------Teacher类中使用Annotation

2、设置表结构,创建数据库和数据表

create database hibernate;

use hibernate;

create table teacher(
	id int primary key,
	name varchar(20),
	title varchar(20)
);

3、设置Hibernate配置文件hibernate.cfg.xml,其位置位于src下

<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- 连接的数据库的url -->
		<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
		<!-- 连接的数据库的用户名-->
		<property name="connection.username">root</property>
		<!-- 连接的数据库的密码 -->
		<property name="connection.password"></property>
		<!-- 配置Hibernate数据库方言 -->
		<property name="Dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 输出执行的SQL语句 -->
        <property name="show_sql">true</property>
		<!-- 启动时撤销并重新创建数据库的模式 -->
		<property name="hbm2ddl.auto">update</property>

		<mapping class="com.model.Teacher"/>
	</session-factory>
</hibernate-configuration>

4、建立测试类,测试

package com.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.model.Teacher;

public class TeacherTest  {
	public static void main(String[] args) {
		Teacher teacher = new Teacher();
		teacher.setId(2);
		teacher.setName("黎明");
		teacher.setTitle("教授");
		
		Configuration cfg = new Configuration();
		cfg.configure();
		ServiceRegistry  sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); 
		SessionFactory  sf = cfg.buildSessionFactory(sr);
		Session s = sf.openSession();
		Transaction tx = s.beginTransaction();
		
		s.save(teacher);
		tx.commit();
		s.close();
		sf.close();
	}
}

5、运行测试类,并查看表中是否已添加一条数据记录,且后台输出执行的SQL语句:Hibernate: insert into Teacher (name, title, id) values (?, ?, ?)。

注意:项目建立时需将Hibernate的jar包(位于hibernate-release-4.1.2.Final\lib\required下的所有包)和MySQL的JDBC的包导入到项目中去;

cfg.configure()默认配置文件为hibernate.cfg.xml,即cfg.configure()等价于cfg.configure("hibernate.cfg.xml"),若配置文件不是这个名则必须指定配置文件名。

-------------------------------------------------------------------------------------------------------------------

其中,org.hibernate.cfg.AnnotationConfiguration已经弃用,直接使用org.hibernate.cfg.Configuration即可,创建语句Configuration cfg = new Configuration()而不是AnnotationConfiguration cfg = new AnnotationConfiguration()。





 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 与 MySQL 结合使用 JPA (Java Persistence API) 的步骤如下: 1. **添加依赖**: 在你的 Maven 或 Gradle 项目中,添加 Spring Data JPA 和 MySQL 驱动的依赖。例如,Maven 项目的 `pom.xml` 中添加: ```xml <dependencies> ... <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <!-- only needed at runtime --> </dependency> ... </dependencies> ``` 2. **配置数据库**: 在 `application.properties` 或 `application.yml` 文件中配置数据库连接信息,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=myuser spring.datasource.password=mypassword spring.jpa.hibernate.ddl-auto=update ``` 3. **定义实体类**: 创建一个或多个 Java 实体类(Entity Class),继承自 `javax.persistence.Entity`,并包含字段和标识器(id)。 4. **定义Repository接口**: 使用 Spring Data JPA 提供的 JpaRepository 接口来操作数据库,例如: ```java import org.springframework.data.jpa.repository.JpaRepository; public interface MyEntityRepository extends JpaRepository<MyEntity, Long> { } ``` 5. **注入 Repository**: 在需要使用 JPA 的服务或控制器类中,使用 `@Autowired` 注入 Repository 类: ```java import org.springframework.beans.factory.annotation.Autowired; @Service public class MyService { private final MyEntityRepository repository; @Autowired public MyService(MyEntityRepository repository) { this.repository = repository; } // 使用 repository 进行数据库操作的方法 } ``` 6. **运行应用**: 启动 Spring Boot 应用,JPA 将自动配置并处理与数据库的交互。 相关问题-- 1. JPA 中的 `@Entity`、`@Table`注解分别代表什么? 2. 如何在 Spring Boot 中启用 Hibernate 作为 JPA 的默认实现? 3. JPA 提供了哪些基本操作,如查询、插入、更新和删除?

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值