总依赖组件坐标:
<properties> <spring.version>5.2.8.RELEASE</spring.version> <hibernate.version>5.0.7.Final</hibernate.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.1.Final</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>2.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies>
设置一个配置类的包
cn.xxx.config
设置总配置加载类
package cn.echo42.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** * @author DaiZhiZhou * @file SpringDataJpa * @create 2020-07-31 10:20 */ @Configuration @Import({SpringDataJpaConfiguration.class,DataSourceConfiguration.class}) @ComponentScan("cn.echo42") public class ApplicationConfiguration { }
其中导入了数据源和SpringDataJpa的配置类
数据源配置:
太懒,没写配置文件了
package cn.echo42.config; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.beans.PropertyVetoException; /** * @author DaiZhiZhou * @file SpringDataJpa * @create 2020-07-31 10:22 */ @Configuration public class DataSourceConfiguration { @Bean("dataSource") public DataSource getDataSource( @Value("com.mysql.cj.jdbc.Driver") String driverClass, @Value("jdbc:mysql:///oa?serverTimezone=Asia/Shanghai") String url, @Value("root") String user, @Value("123456") String password) throws PropertyVetoException { ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); comboPooledDataSource.setDriverClass(driverClass); comboPooledDataSource.setJdbcUrl(url); comboPooledDataSource.setUser(user); comboPooledDataSource.setPassword(password); return comboPooledDataSource; } }
SpringDataJpa配置:
package cn.echo42.config; import org.hibernate.jpa.HibernatePersistenceProvider; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaDialect; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; /** * @author DaiZhiZhou * @file SpringDataJpa * @create 2020-07-31 11:06 */ @Configuration //@Import(DataSourceConfiguration.class) @EnableJpaRepositories( basePackages = "cn.echo42.dao", transactionManagerRef = "jpaTransactionManager", entityManagerFactoryRef = "entityManagerFactory" ) public class SpringDataJpaConfiguration { @Bean("persistenceProvider") /* Jpa实现者 即规范供应商 */ public HibernatePersistenceProvider getProvider(){ return new HibernatePersistenceProvider(); } @Bean("jpaDialect") /* Jpa方言对象 */ public HibernateJpaDialect getHibernateJpaDialect(){ return new HibernateJpaDialect(); } @Bean("adapter") /* 实现者适配器 */ public HibernateJpaVendorAdapter getHibernateJpaVendorAdapter(){ HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); adapter.setDatabase(Database.MYSQL); adapter.setGenerateDdl(false); adapter.setShowSql(true); adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect"); return adapter; } @Bean("entityManagerFactory") public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryBean ( DataSource dataSource, @Value("cn.echo42.entity") String scanPath, HibernatePersistenceProvider hibernatePersistenceProvider, HibernateJpaDialect hibernateJpaDialect) { LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setPackagesToScan(scanPath); factoryBean.setPersistenceProvider(hibernatePersistenceProvider); factoryBean.setJpaDialect(hibernateJpaDialect); return factoryBean; } @Bean("jpaTransactionManager") /* Jpa事务管理器 */ public JpaTransactionManager getJpaTransactionManager(EntityManagerFactory factoryBean) { JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(); jpaTransactionManager.setEntityManagerFactory(factoryBean); return jpaTransactionManager; } }
用户实体类:
package cn.echo42.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; /** * @author DaiZhiZhou * @file SpringDataJpa * @create 2020-07-31 10:54 */ @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "sys_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer user_id; // @Column(name = "user_id") private String user_name; // @Column(name = "user_name") private String user_password; // @Column(name = "user_password") private Integer user_status; // @Column(name = "user_status") private Integer user_is_del; // @Column(name = "user_is_del") }
用户持久化接口:
package cn.echo42.dao; import cn.echo42.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * @author DaiZhiZhou * @file SpringDataJpa * @create 2020-07-31 10:58 */ public interface UserDao extends JpaRepository<User,Integer> , JpaSpecificationExecutor<User> { }
最后的测试类:
import cn.echo42.config.ApplicationConfiguration; import cn.echo42.dao.UserDao; import cn.echo42.entity.User; 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 java.util.List; /** * @author DaiZhiZhou * @file SpringDataJpa * @create 2020-07-31 10:52 */ @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = "classpath:Bean-Context.xml") // XML加载 @ContextConfiguration(classes = ApplicationConfiguration.class) // JavaConfig public class SpringDataJpaTest { @Autowired private UserDao userDao; @Test public void quickStart(){ List<User> userList = userDao.findAll(); for (User user : userList) { System.out.println(user); } } }
测试结果:
User(user_id=1, user_name=admin, user_password=admin, user_status=1, user_is_del=0) User(user_id=2, user_name=user01, user_password=123456, user_status=1, user_is_del=0) User(user_id=3, user_name=user02, user_password=123456, user_status=1, user_is_del=0) User(user_id=4, user_name=user03, user_password=123456, user_status=1, user_is_del=0) User(user_id=5, user_name=admin02, user_password=admin02, user_status=1, user_is_del=0)
如果需要日志打印:
在Resource目录种配置日志【log4j.properties】
log4j.rootLogger=DEBUG,console,file # Settings About ConsoleOutput log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.Target=System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n # Settings About FileOutput log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=./resources/log/logging.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n # LogOutput Level log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG