Spring_hibernate整合初步 based in annotation

首先配置xml

<bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
     <property name="annotatedClasses">
       <list>
         <value>com.chpn.model.User</value>
       </list>
     </property>
     <property name="hibernateProperties">
      <props>
         <prop key="hibernate.dialect">
          org.hibernate.dialect.MySQLDialect
         </prop>
         <prop key="hibernate.show_sql">
          true
         </prop>
     </props>

     </property>
  </bean>
 

建立實體類,加上annotation

@Entity
public class User {
 int id;
 String name;
 
 @Id
 @GeneratedValue
 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;
 }
 
}

在UserDaoImpl.java中寫有關hibernate邏輯

@Component("user")
public class UserDAOImpl implements UserDAO {

 private SessionFactory sessionFactory;

 public SessionFactory getSessionFactory() {
  return sessionFactory;
 }
 
 @Resource
 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 @Override
 public void save(User u) {
   Session s = sessionFactory.openSession();
   s.beginTransaction();
   s.save(u);
   s.getTransaction().commit();
   

   // TODO Auto-generated catch block

  System.out.println("user save");
 }

}

引入hibernate相關jar包

 

至此Spring整合hibernate初步完成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章