HelloWorld(XML/annotation)
在hibernate.cfg.xml中两种版本的HelloWorld的配置
<mapping resource="com/m4java/hibernate/model/Student.hbm.xml" /> <mapping class="com.m4java.hibernate.model.Teacher"/>
1.XML版
在pojo类包下写一个相应的.hbm.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 package="com.m4java.hibernate.model">
<class name="Student" table="student">
<id name="id">
<!-- oralce中主键自增长的配置方式: -->
<generator class="sequence" >
<param name="sequence">student_id_seq</param>
</generator>
</id>
<property name="name"></property>
<property name="age"></property>
</class>
</hibernate-mapping>测试方法:Student s=new Student();
s.setName("s4");
s.setAge(3);
Configuration cfg=new Configuration();
SessionFactory sf=cfg.configure().buildSessionFactory();//获取配置,拿到SessionFactory
Session session=sf.openSession();//获得Session
session.beginTransaction();//开始事务
session.save(s);//保存对象
session.getTransaction().commit();//提交
session.close();//关闭资源
sf.close();cfg.configure()方法要求hibernate.cfg.xml存放在src目录下,也可以自己指定,具体的可查看相关API。
2.annotation
这个版本相对简单些,主要在pojo类中使用注解,注意引用的包为javax.persistence.XXXXX
@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;
}
}测试方法跟XML的一样。
关于在oracle中实现主键自增长:
首先在oracle中创建一个sequence-->createsequencetestminvalue1maxvalue100startwith1incrementby1;
在配置文件中如下配置即可:
<id name="id"> <!-- oralce中主键自增长的配置方式: --> <generator class="sequence" > <param name="sequence">test</param> </generator> </id>
相关推荐
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
XGQ 2020-07-04
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16
wcqwcq 2020-06-14
yuanye0 2020-06-14
zhongliwen 2020-06-13
MrFuWen 2020-06-09