直接上(默认什么都配置好了的哦)
mark-1:准备数据类
//这是一个学生成绩类
public class Score {
private int id;
private int stuId;//学生编号
private int subjectId;//科目编号
private double result;//成绩
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public int getSubjectId() {
return subjectId;
}
public void setSubjectId(int subjectId) {
this.subjectId = subjectId;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
}
mark-2: 配置him.xml文件
<?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>
<class name="com.hibernate.zuhekey.Score" table="Score">
<id name="id">
<!-- 主键生成策略 -->
<generator class="native"></generator>
</id>
<!-- 实体类的属性 -->
<property name="stuId"/>
<property name="subjectId"/>
<property name="result"/>
</class>
</hibernate-mapping>
mark-3:配置hibernate.cfg.xml文件
<!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>
<!--配置要连接的数据库地址-->
<property name="connection.url">
jdbc:mysql://localhost:3306/hibernate4
</property>
<!--配置用户名和密码-->
<property name="connection.username">root</property>
<property name="connection.password”>root</property>
<!-- 数据库方言 -->
<property name="dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- 将hibernate生成的sql语句打印到控制台 -->
<property name="hibernate.show_sql">true</property>
<!-- 将hibernate生成的sql语句格式化(语法缩进) -->
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 引入orm元数据
路径书写: 填写src下的路径
-->
<!-- 有几个pojo类就配置几个资源路径 -->
<mapping resource="com/hibernate/demo/User.hbm.xml" />
<mapping resource="com/hibernate/demo/Product.hbm.xml"/>
<mapping resource="com/hibernate/cust/Customer.hbm.xml"/>
<mapping resource="com/hibernate/zuhekey/Score.hbm.xml"/>
</session-factory>
mark-4: 利用hibernate生成对应数据表
public static void main(String[] args){
Configuration config = new Configuration().configure();
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure().build();
Metadata metadata = new MetadataSources(serviceRegistry)
.buildMetadata();
SchemaExport schemaExport = new SchemaExport();
schemaExport.create(EnumSet.of(TargetType.DATABASE), metadata);
}
5.0之前的写法过期了: