【hibernate】hibernate配置及实例(sqlsever)
原创
©著作权归作者所有:来自51CTO博客作者heituan的原创作品,请联系作者获取转载授权,否则将追究法律责任
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="hibernate.connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:sqlserver://localhost:1433;DatabaseName=db_test
</property>
<property name="hibernate.connection.username">
sa
</property>
<property name="hibernate.connection.password">
157147
</property>
<!-- List of XML mapping files -->
<mapping resource="hibernateTest/Info.hbm.xml"/>
<!-- 修改实体类名.hbm.xml文件 -->
</session-factory>
</hibernate-configuration>
映射文件xx.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernateTest.Info" table="tb_test">
<meta attribute="class-description">
Info类和数据库关系映射
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
</class>
实体类:Info.java
package hibernateTest;
public class Info {
private int id;
private String name;
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;
}
}
主方法类:
package hibernateTest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class MainTest {
public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure("hibernateTest/hibernate.cfg.xml");//加载配置文件
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Transaction tx=session.beginTransaction();//开启事务
Info info = new Info();
info.setName("bb");//添加信息
session.save(info);//保存信息
tx.commit();//事务提交
session.close();
sf.close();
System.out.println(info.getName());
}
}