hibernate正向生成数据库表以及配置——TestStu.java
2023-09-14 08:57:41 时间
package cn.bdqn.studentInfo.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cn.bdqn.studentInfo.entity.Student;
import cn.bdqn.studentInfo.entity.Teacher;
/**
* 测试类
* @author Administrator
*
*/
public class testStu {
private Configuration conf=null;
private SessionFactory sessionFac=null;
private Session session=null;
private Transaction tx=null;
/**
* 正向创建数据表
*/
@Test
public void createDB(){
Configuration conf=new Configuration()
.configure();
SchemaExport export =new SchemaExport(conf);
export.create(true, true);
}
/**
* 测试
*/
@Test
public void testMethod(){
Session session=new Configuration().configure().buildSessionFactory().openSession();
Transaction tx=session.beginTransaction();
try{
//创建两个学生对象
Student student1=new Student();
student1.setName("张同学");
student1.setId(9);
Student student2=new Student();
student2.setName("王同学");
student2.setId(10);
//创建两个老师对象
Teacher teacher1=new Teacher();
teacher1.setId(9);
teacher1.setName("武老师");
Teacher teacher2=new Teacher();
teacher2.setId(10);
teacher2.setName("程老师");
/**
* 关联双方的关系
*/
//告诉张同学,武老师和程老师都带着你的课
student1.getTeachers().add(teacher1);
student1.getTeachers().add(teacher2);
//告诉王同学,武老师和程老师都带着你的课
student2.getTeachers().add(teacher1);
student2.getTeachers().add(teacher2);
//告诉武老师,你现在带着王、张同学的课
teacher1.getStudents().add(student1);
teacher1.getStudents().add(student2);
//告诉程老师,你现在带着王、张同学的课
teacher2.getStudents().add(student1);
teacher2.getStudents().add(student2);
//添加
session.save(student1);
session.save(student2);
/*session.save(teacher1);
session.save(teacher2);*/
tx.commit();
}catch (Exception e) {
tx.rollback();//添加失败时,进行回滚
e.printStackTrace();
}
}
/**
* 关闭session
*/
@After
public void closeSession(){
if(session!=null){
session.close();
}
}
}
相关文章
- [Java基础] java多线程关于消费者和生产者
- MySQL_(Java)使用JDBC向数据库中删除(delete)数据
- JAVA-数据库之Statement对象
- JAVA-数据库之JDBC连接MySQL数据库
- JAVA-数据库之MySQL与JDBC驱动下载与安装
- [java] - 数据库连接工具类
- hibernate正向生成数据库表以及配置——TestStu.java
- hibernate正向生成数据库表以及配置——Teacher.java
- JAVA学习(三):Java基础语法(变量、常量、数据类型、运算符与数据类型转换)
- Java实现John's trip(约翰的小汽车)
- Java实现 蓝桥杯VIP 基础练习 Huffuman树
- 【JAVA】java中split以"." 、""、“|”分隔字符串
- Java基础篇2——运算符
- Java Annotation详解 理解和使用Annotation
- 不使用spring的情况下用java原生代码操作mongodb数据库的两种方式
- Atitit. 数据库-----catalog与schema的设计区别以及在实际中使用 获取数据库所有库表 java jdbc php c#.Net
- Java中dao层、service层、controller层、entity层和view层的概述
- 【java】Java 包(package)
- Spring Boot 应用监控: Java获取 CPU,内存, JVM 内部运行状况代码
- Java删除数据库中的数据
- [Sqlite]-->Java采用jdbc联系Sqlite各种特定的工艺数据库的数据操作
- Java开发入门到精通之Java的数据库访问
- 【java】Java 中泛型的实现原理