实现数据库表和javabean类的映射关系
<hibernate-configuration> <session-factory> <!-- 数据源定义 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver </property> <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456 </property> <!--class 数据库表的描述文件”--> <mapping resource="org/mxg/Class.hbm.xml"></mapping> <!--user_info 数据库表的描述文件”--> <mapping resource="org/mxg/UserInfo.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
<!--描述了数据库class表 到 javabean中字段的对应关系--> <hibernate-mapping> <class name="entity.Class" table="t_class"> <id name="id" type="integer"> <column name="id"></column> <generator class="native"></generator> </id> <property name="name"> <column name="name"></column> </property> <property name="pwd"> <column name="pwd"></column> </property> <property name="age"> <column name="age"></column> </property> </class> </hibernate-mapping> <!--描述了数据库user_info表 到 javabean中字段的对应关系--> <hibernate-mapping> <class name="entity.UserInfo" table="t_user_info"> <id name="id" type="integer"> <column name="id"></column> <generator class="native"></generator> </id> <property name="name"> <column name="name"></column> </property> <property name="pwd"> <column name="pwd"></column> </property> <property name="age"> <column name="age"></column> </property> </class> </hibernate-mapping>
public class UserInfo{ private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; }
public static void main(String[] args) { Session session = SessionFactoryUtil.getInstance().getCurrentSession(); Transaction tx = session.beginTransaction(); User user = new User();//瞬态 user.setId("aaa"); session.save(user);//持久态 }