這次實(shí)踐的內(nèi)容是數(shù)據(jù)庫(kù)連接瘾带,自動(dòng)規(guī)范查詢蹦狂,分頁(yè)慨菱。
--本來沒有數(shù)據(jù)庫(kù)連接 卻連了一天
這里從連接到Mvc記錄一遍挟炬。
開始是數(shù)據(jù)庫(kù)配置鸥滨。
用properties的話特別特別注意
要先指定該文件的目錄再用:
Properties prop =newProperties();StringrealPath =“.properties”//相對(duì)絕對(duì)路徑都可以嗦哆,但是要有properties;Stringvalue= prop.getProperty("goopalpayPay_key").toString();
或者用@PropertySource(value ="file:E:/dev-chinagpay.properties")
@AutowiredprivateEnvironment env;
但我都沒成功婿滓,相對(duì)路徑絕對(duì)路徑都試了老速,大神知道請(qǐng)指點(diǎn)。
首先應(yīng)該配置的是datasource 一般我都用ComboPooledDataSource來配置凸主,ComboPooledDataSource dataSource = new ComboPooledDataSource();
? ? ? ? dataSource.setDriverClass("com.mysql.jdbc.Driver");
? ? ? ? dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
? ? ? ? dataSource.setUser("root");
? ? ? ? dataSource.setPassword("root");
? ? ? ? dataSource.setMaxPoolSize(20);
? ? ? ? dataSource.setMinPoolSize(5);
? ? ? ? dataSource.setInitialPoolSize(10);
? ? ? ? dataSource.setMaxIdleTime(300);
? ? ? ? dataSource.setAcquireIncrement(5);
? ? ? ? dataSource.setIdleConnectionTestPeriod(60);
獲得datasource之后才是獲得EntityManagerFactory(這東西類似session工廠橘券,可用它獲得Entitymanager)。
@Bean? ? public EntityManagerFactory entityManagerFactory() {
? ? ? HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
? ? ? LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();? ? ? ? factory.setJpaVendorAdapter(vendorAdapter);? ? ? ? //此處com.example.*.model是你的java bean所在的包名
? ? ? ? factory.setPackagesToScan("com.there.Webpro");
? ? ? factory.setDataSource(dataSource);? ? ? ? MapjpaProperties = new HashMap();
? ? ? ? factory.setJpaPropertyMap(jpaProperties);
? ? ? ? factory.afterPropertiesSet();
? ? ? ? return factory.getObject();
? ? }
然后需要配置事務(wù)卿吐,沒有事務(wù)是運(yùn)行不起來的旁舰。
@Bean
? ? public PlatformTransactionManager transactionManager() {
? ? ? ? JpaTransactionManager txManager = new JpaTransactionManager();
? ? ? ? txManager.setEntityManagerFactory(entityManagerFactory());
? ? ? ? return txManager;
? ? }
現(xiàn)在數(shù)據(jù)庫(kù)就配置完了
現(xiàn)在是將一些繼承類
jpa好處是你繼承了一些類,甚至在DAO層不需要實(shí)現(xiàn)也能經(jīng)行操作
(1) CrudRepository: 繼承 Repository嗡官,實(shí)現(xiàn)了一組 CRUD 相關(guān)的方法
(2)PagingAndSortingRepository: 繼承 CrudRepository箭窜,實(shí)現(xiàn)了一組分頁(yè)排序相關(guān)的方法
(3)JpaRepository: 繼承 PagingAndSortingRepository,實(shí)現(xiàn)一組 JPA 規(guī)范相關(guān)的方法
分頁(yè)查詢
分頁(yè)查詢我測(cè)試是直接用在規(guī)范方法中衍腥,自己寫的方法里我還沒有用過磺樱。
傳入DAO操作函數(shù)一個(gè) pageable ,可以從多處獲取它。
自己new PageRequest(第幾頁(yè)婆咸,每頁(yè)數(shù)據(jù))或者在控制器中直接傳入Pageable
獲得的多個(gè)數(shù)組可以用Page<T>來裝竹捉。
我的錯(cuò)誤集中在獲取上下文的時(shí)候,報(bào)錯(cuò):沒有該文件尚骄。這是怎么回事块差。我的問題是,沒有在配置類上加@compentscan