假设我们有一张student表,结构很简单:
- id 自动增长
- name varchar(40)
- password varchar(32)
- grade int(4) 年级
- sex Boolean 性别(true为男,false为女)
设计一个Student类来映射这张表:
- /*
- * 创建日期 2005-3-17
- */
- package net.bromon.spring.examer.pojo;
-
- /**
- * @author Bromon
- */
- public class Student
- {
- private int id;
- private String name;
- private String password;
- private int grade;//年级
- private boolean sex;
-
- getset方法……….
- }
编写Student.hbm.xml,让hibernate知道如何去关联student表和Student类,该文件和Student.java在同一目录:
- <hibernate-mapping>
- <class name="net.bromon.spring.examer.pojo.Student" table="student">
- <id name="id" column="id">
- <generator class="identity"/>
- </id>
-
- <property name="name" column="name" />
- <property name="password" column="password" />
- <property name="grade" column="grade" />
- <property name="sex" column="sex" />
- </class>
- </hibernate-mapping>
然后我们可以在spring中配置sessionFactory:
- <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
- <property name="dataSource">
- <ref bean="dataSource"/>
- </property>
-
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>
- </props>
- </property>
-
- <property name="mappingDirectoryLocations">
- <list>
- <value>classpath:/netbromonspringexamerpojo</value>
- </list>
- </property>
- </bean>
其中引用了我们之前注册过的dataSource,mappingDirectoryLocations属性指明了.hbm.xml文件在哪里路径,该文件夹下面的.hbm.xml文件会被全部加载。
一切都准备就绪,现在我们要加入一个StudentManager类,来进行增删查改的操作:
- /*
- * 创建日期 2005-3-17
- */
- package net.bromon.spring.examer.student;
-
- import net.bromon.spring.examer.pojo.Student;
-
- import org.springframework.orm.hibernate.HibernateTemplate;
- import org.springframework.orm.hibernate.LocalSessionFactoryBean;
- import org.springframework.orm.hibernate.support.HibernateDaoSupport;
-
- /**
- * @author Bromon
- */
- public class StudentManager extends HibernateDaoSupport
- {
- private LocalSessionFactoryBean sessionFactory;
- private HibernateTemplate ht;
- public StudentManager()
- {
- this.ht=super.getHibernateTemplate();
- }
-
- public void add(Student s)
- {
- ht.save(s);//插入一条数据只需要这一行代码
- }
- }