好久没有写框架文章了,最近一直都在忙活数据结构,趁着今天有空赶紧写一篇SpringData框架入门。
框架简介
按照惯例,在学习框架之前,当然要先了解框架的作用,看官方定义:
SpringData是Spring的一个子项目,用于简化数据库访问,支持NoSQL和关系数据存储,其主要目的是使数据库的访问变得方便快捷。
SpringData致力于减少数据访问层的开发量,开发者唯一要做的,就只是声明持久层的接口,其它都交给SpringData来帮你完成。
HelloWorld
下面同样是通过一个HelloWorld级的案例来入门SpringData。
创建Java项目,导入Spring、JPA、SpringData、C3P0的jar包和mysql的驱动,因为SpringData是建立在Spring和JPA框架的基础之上的。
在src目录下创建db.properties文件,将数据源信息抽离出来:
jdbc.user=root
jdbc.password=1230
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///jpa
接着创建spring的配置文件,进行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--配置数据源-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
</bean>
</beans>
此时可以测试一下数据源是否配置成功。
public static void main(String[] args){
try {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = ctx.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
} catch (SQLException e) {
e.printStackTrace();
}
}
运行结果:
com.mchange.v2.c3p0.impl.NewProxyConnection@1efee8e7
此时证明代码编写无误,我们继续。
接着对JPA进行配置,如果没有了解过JPA的话,可以看我前面的文章。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--配置数据源-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
</bean>
<!--配置JPA的EntityManagerFactory-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.wwj.springdata"/>
<property name="jpaProperties">
<props>
<!-- 生成的数据表的列的映射策略 -->
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<!-- hibernate 基本属性 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
</beans>
配置完后,我们同样测试一下JPA是否配置成功。
先创建一个持久化类:
package com.wwj.springdata;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "JPA_PERSON")
@Entity
public class Person {
private Integer id;
private String name;
@GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
只需重新运行刚才的程序即可,框架会自动为我们创建持久化类对应的数据表,运行结果如下:
mysql> show tables;
+---------------+
| Tables_in_jpa |
+---------------+
| jpa_person |
+---------------+
1 row in set (0.00 sec)
接下来配置事务管理器、配置事务和SpringData即可:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--配置数据源-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
</bean>
<!--配置JPA的EntityManagerFactory-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.wwj.springdata"/>
<property name="jpaProperties">
<props>
<!-- 生成的数据表的列的映射策略 -->
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<!-- hibernate 基本属性 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--配置支持注解的事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--配置SpringData-->
<jpa:repositories base-package="com.wwj.springdata"
entity-manager-factory-ref="entityManagerFactory"/>
</beans>
项目结构如下:
配置完成后,我们创建一个接口:
package com.wwj.springdata;
import org.springframework.data.repository.Repository;
public interface PersonRepository extends Repository<Person, Integer> {
//根据名字获取信息
Person getByName(String name);
}
通过该方法获取数据表的数据。
我们测试一下:
public static void main(String[] args) {
try {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonRepository personRepository = ctx.getBean(PersonRepository.class);
Person person = personRepository.getByName("aaa");
System.out.println(person);
} catch (Exception e) {
e.printStackTrace();
}
}
运行结果:
Person{
id=1, name='aaa'}
测试成功。
总结
到这里入门案例就编写完成了,可以看到,通过一个接口的抽象方法就可以实现数据表的操作,是不是很神奇呢?想了解SpringData的细节,请看下篇文章。