1. <ul id="0c1fb"></ul>

      <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
      <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区

      RELATEED CONSULTING
      相關咨詢
      選擇下列產品馬上在線溝通
      服務時間:8:30-17:00
      你可能遇到了下面的問題
      關閉右側工具欄

      新聞中心

      這里有您想知道的互聯(lián)網營銷解決方案
      使用Spring4如何實現對Hibernate5進行整合

      使用Spring4如何實現對Hibernate5進行整合?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

      站在用戶的角度思考問題,與客戶深入溝通,找到白云鄂網站設計與白云鄂網站推廣的解決方案,憑借多年的經驗,讓設計與互聯(lián)網技術結合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:網站設計制作、成都網站制作、企業(yè)官網、英文網站、手機端網站、網站推廣、域名與空間、虛擬空間、企業(yè)郵箱。業(yè)務覆蓋白云鄂地區(qū)。

      Spring與Hiberante整合

      通過hibernate的學習,我們知道,hibernate主要在hibernate.cfg.xml配置文件中

      接下來我們看一下hibernate的一個配置文件

      hibernate配置文件

      hibernate.cfg.xml

      <?xml version="1.0" encoding="UTF-8"?>
      
      
        
          
          com.MySQL.jdbc.Driver
          
          jdbc:mysql://localhost/hibernate_test
          
          root
          
          cheng
          
          20
          
          1
          
          5000
          
          100
          3000
          2
          true
          
          org.hibernate.dialect.MySQL5InnoDBDialect
          
          update
          
          true
          
          true
          
          false
          
          
          
        
      

      配置文件的作用

      hibernate.cfg.xml文件的主要作用就是配置了一個session-factory

      1. 在session-factory中主要通過property配置一些數據庫的連接信息,我們知道,spring通常會將這種數據庫連接用dataSource來表示,這樣一來,hibernate.cfg.xml文件中的所有跟數據庫連接的都可以干掉了,直接用spring的dataSource,而dataSource也可以用c3p0、dbcp等。
      2. 在session-factory中通過property除了配置一些數據庫的連接信息之外,還有一些hibernate的配置,比如方言、自動創(chuàng)建表機制、格式化sql等,這些信息也需要配置起來。
      3. 還有最關鍵的一個持久化類所在路徑的配置

      當不采用spring整合的時候,我們使用hibernate時主要是用hibernate從sessionFactory中去的session,然后用session來操作持久化對象,而sessionFactory來自于配置文件。像下面這樣:

        StandardServiceRegistry registry = null;
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction transaction = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      
        @Before
        public void init() {
      
          registry = new StandardServiceRegistryBuilder()
              .configure() // configures settings from hibernate.cfg.xml
              .build();
          sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
          session = sessionFactory.openSession();
          //開始事務
          transaction = session.getTransaction();
          transaction.begin();
        }
      
        @Test
        public void testSaveUser() {
          User user = new User();
          user.setUsername("張學友");
          user.setPassword("jacky");
          user.setRegistDate(sdf.format(new Date()));
          File file = new File("D:"+File.separator+"ubuntu.png");
          String fileName = file.getName();
          String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
          System.out.println(prefix);
          InputStream input = null;
          try {
            input = new FileInputStream(file);
      
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          }
      
          Blob image = null;
          try {
            image = Hibernate.getLobCreator(session).createBlob(input,input.available());
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          user.setUserPic(image);
          session.save(user);
        }
      
        @After 
        public void destroy(){
          transaction.commit();
          session.close();
          sessionFactory.close();
          StandardServiceRegistryBuilder.destroy( registry );
        }

      Spring對hibernate的整合就是將上述三點通過spring配置起來,而hibernate最關鍵的sessionFactroy就是spring的一個bean

      這些理解了整合就簡單了,

      SessionFactoryBean

      spring的sessionFactroy像下面這樣配置:

      
        
      
        
          
          
            
              
              com.wechat.entity.po
            
          
          
            
              ${hibernate.hbm2ddl.auto}
              ${hibernate.dialect}
              ${hibernate.show_sql}
              ${hibernate.format_sql}
              false
            
          
        

      通過bean的配置可以看出該bean就是hibernate的sessionFactroy

      因為它指向了org.springframework.orm.hibernate5.LocalSessionFactoryBean

      在這個bean中主要配置了上面說的三點:

      1. 數據源dataSource
      2. hibernate的配置,包括方言,輸出sql等
      3. 持久化類的位置,通過包進行掃描

      下面給出數據源dataSource的配置

      dataSource

      
        

      還有數據庫的連接信息

      jdbc.properties

      #-----------------------------------------------------
      # 數據庫配置
      #-----------------------------------------------------
      #服務器地址
      host=127.0.0.1
      jdbc.driverClassName=com.mysql.jdbc.Driver
      jdbc.url=jdbc:mysql://${host}:3306/hibernate_test
      jdbc.username=root
      jdbc.password=cheng
      
      #-----------------------------------------------------
      # 適用于c3p0的配置
      #-----------------------------------------------------
      #-----------------------------------------------------
      # c3p0反空閑設置,防止8小時失效問題28800
      #-----------------------------------------------------
      #idleConnectionTestPeriod要小于MySQL的wait_timeout
      jdbc.c3p0.testConnectionOnCheckout=false
      jdbc.c3p0.testConnectionOnCheckin=true
      jdbc.c3p0.idleConnectionTestPeriod=3600
      #-----------------------------------------------------
      # c3p0連接池配置
      #-----------------------------------------------------
      #initialPoolSize, minPoolSize, maxPoolSize define the number of Connections that will be pooled.
      #Please ensure that minPoolSize <= maxPoolSize.
      #Unreasonable values of initialPoolSize will be ignored, and minPoolSize will be used instead.
      jdbc.c3p0.initialPoolSize=10
      jdbc.c3p0.minPoolSize=10
      jdbc.c3p0.maxPoolSize=100
      #maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool.
      jdbc.c3p0.maxIdleTime=3600
      #-----------------------------------------------------
      # hibernate連接池配置
      #-----------------------------------------------------
      hibernate.connection.driverClass=com.mysql.jdbc.Driver
      hibernate.connection.url=jdbc:mysql://${host}:3306/${dbName}
      hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
      hibernate.show_sql=true
      hibernate.format_sql=true
      hibernate.hbm2ddl.auto=update

      配置完這些還有spring強大的事務管理

      
        
          
        
      
        
        
      
        
        
      
        
        
        
          
          
          
          
        
        
        
          
          
            
          
        

      好了,這些配置好之后就可以使用在spring中配置的sessionFactroy了

      UserDao

      package com.wechat.dao;
      
      import java.util.List;
      
      import com.wechat.entity.po.User;
      
      public interface UserDao {
        // 得到所有用戶
        public List getAllUser();
      
        // 檢測用戶名是否存在
        public boolean isExists(String username);
      
      }

      實現類

      package com.wechat.dao.impl;
      
      import java.util.ArrayList;
      import java.util.List;
      
      import org.hibernate.Query;
      import org.hibernate.Session;
      import org.hibernate.SessionFactory;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Repository;
      
      import com.wechat.dao.UserDao;
      import com.wechat.entity.po.User;
      @Repository
      public class UserDaoImpl implements UserDao {
        //注入sessionFactory
        @Autowired
        private SessionFactory sessionFactory;
      
        @SuppressWarnings("unchecked")
        @Override
        public List getAllUser() {
          List userList = new ArrayList();
          String hsql="from User";
          Session session = sessionFactory.getCurrentSession();
          Query query = session.createQuery(hsql);
          userList = query.list();
          return userList;
        }
      
        @Override
        public boolean isExists(String username) {
          Query query = sessionFactory.openSession()
              .createQuery("from User u where u.username = :username").setParameter("username", username);
          System.out.println(query.list().size());
          return query.list().size()>0?true:false;
        }
      
      }

      UserService

      package com.wechat.service.user;
      
      import java.util.List;
      
      import com.wechat.entity.po.User;
      
      public interface UserService {
        public List getAllUser();
        public boolean isExists(String username);
      
      }

      實現類

      package com.wechat.service.user.impl;
      
      import java.util.List;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.cache.annotation.Cacheable;
      import org.springframework.stereotype.Service;
      
      import com.wechat.dao.UserDao;
      import com.wechat.entity.po.User;
      import com.wechat.service.user.UserService;
      @Service
      public class UserServiceImpl implements UserService {
        @Autowired
        private UserDao userDao;
        @Override
        public List getAllUser() {
          return userDao.getAllUser();
        }
        @Override
        @Cacheable(cacheNames="isExists", key="#username")
        public boolean isExists(String username) {
          return userDao.isExists(username);
        }
      
      }

      因為事務管理是配置在service層,所以用service來測試

      測試

      package com.wechat.dao;
      
      import java.util.List;
      
      import org.junit.Test;
      import org.junit.runner.RunWith;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.test.context.ContextConfiguration;
      import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
      
      import com.wechat.entity.po.User;
      import com.wechat.service.user.UserService;
      
      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(locations = { "classpath:spring/spring-core.xml" })
      public class UserServiceTest {
        @Autowired
        private UserService userService;
      
        @Test
        public void test() {
          List userList = userService.getAllUser();
          for(User user:userList){
            System.out.println(user.getUsername());
          }
      
        }
      
      }

      輸入結果

      Hibernate: 
        select
          user0_.userid as userid1_2_,
          user0_.password as password2_2_,
          user0_.registDate as registDa3_2_,
          user0_.userPic as userPic4_2_,
          user0_.username as username5_2_ 
        from
          user_info user0_
      程高偉
      張學友

      數據庫表

      使用Spring4如何實現對Hibernate5進行整合

      看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。


      網站欄目:使用Spring4如何實現對Hibernate5進行整合
      URL標題:http://www.ef60e0e.cn/article/posoos.html
      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区
      1. <ul id="0c1fb"></ul>

        <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
        <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

        嘉鱼县| 深泽县| 南皮县| 杨浦区| 襄汾县| 县级市| 双牌县| 西峡县| 梁山县| 新化县| 兰州市| 清苑县| 中卫市| 万源市| 昆山市| 独山县| 蓬莱市| 江孜县| 鄯善县| 临夏县| 吕梁市| 嘉黎县| 蒙山县| 甘孜县| 彭山县| 龙游县| 汶上县| 宁津县| 灯塔市| 治县。| 葫芦岛市| 盖州市| 平潭县| 碌曲县| 新兴县| 和龙市| 六枝特区| 喀喇沁旗| 手游| 涡阳县| 秦皇岛市|