【SpringDataJPA】——SpringDataJPA入门实例

简介:   Spring经常喜欢做的事情就是封装,经过spring的封装结出的一大果实——SpringDataJPA可以很大程度上提高我们持久层的开发效率。

 Spring经常喜欢做的事情就是封装,经过spring的封装结出的一大果实——SpringDataJPA可以很大程度上提高我们持久层的开发效率。

 在SpringDataJPA下,只需要关注业务实现,无需关注持久层的逻辑,需要做的工作只是声明持久层的接口,并不需要亲自实现,实现接口这些工作SpringDataJPA都会帮你做好。它有个比较智能的特点,可以根据接口名称来判断你想进行的操作。比如针对UserDO定义如下一个Dao层接口:


public class UserDO{
    private Long id;
    private String name;
}
public interface UserDAO extends PagingAndSortingRepository<UserDO,Long>{
    public UserDO findUserById(Long id);
    public UserDO findUserByIdAndName(Long id,String name)
}


 仅仅需要定义上面的接口,不需要任何实现,调用的时候SpringDataJPA会自动根据findUserById方法的名字判断出来是根据id查询用户,根据findUserByIdAndName判断出是根据id和name查询用户,前提是接口名称需要遵守规范,SpringDataJPA就规定了方法命名的规范,规定方法前缀(find、read、get)、字段命名格式(字段首字母大写)、关键字(And、Or……),详细规范可参考《Spring Data JPA方法定义规范》、《SpringDataJPA方法命名与操作对照》。

 下面主要分享个入门时的小例子:

 实体类UserDO.java


@Entity
@Table(name="t_user")
public class UserDO extends BaseEntity{
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
    @Column(name = "name")
    private String name;
    public Long getId() {
        return id;
    }
    public UserDO setId(Long id) {
        this.id = id;
        return this;
    }
    public String getName() {
        return name;
    }
    public UserDO setName(String name) {
        this.name = name;
        return this;
    }
}


  对应接口UserDAO.java

public interface UserDAO extends PagingAndSortingRepository<UserDO,Long> {
    public UserDO findById(Long id);
    public UserDO findByIdAndName(Long id,String name);
}


  SpringDataJPA配置文件applicationContext-persistence.xml、


<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       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-3.2.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.2.xsd
      http://www.springframework.org/schema/data/jpa
      http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">
    <context:component-scan base-package="com.danny.springdata.dao"/>
    <bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.danny.springdata.entities"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <!-- 自动建表 -->
                <prop key="hibernate.ddl-auto">update</prop>
            </props>
        </property>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springdatajpa"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="myEmf"/>
    </bean>
    <tx:annotation-driven/>
    <bean id="persistenceExceptionTranslationPostProcessor"
          class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
    <jpa:repositories base-package="com.danny.springdata.dao"
                      entity-manager-factory-ref="myEmf"
                      transaction-manager-ref="transactionManager"/>
</beans>


   测试UserDAOTest.java


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext-*.xml"})
public class UserDAOTest{
    @Autowired
    private UserDAO userDAO;
    @Test
    public void findByIdTest() {
        UserDO userDO=userDAO.findById(1L);
        Assert.assertNotNull(userDO);
    }
    @Test
    public void findByIdAndNameTest() {
        UserDO userDO=userDAO.findByIdAndName(1L,"danny");
        Assert.assertNotNull(userDO);
    }
}

仅仅如此,so easy!

  源码地址:git@github.com:DannyHoo/SpringDataJPADemo.git


相关文章
|
JavaScript 索引
vscode中快捷生成自定义vue3模板
vscode中快捷生成自定义vue3模板
3456 1
|
druid Java 关系型数据库
SpringBoot配置Druid数据库连接池
可以选择依赖下载,也可以直接下载jar包,需要注意的一点就是新版本可能不稳定,选择下载量最多的那个版本。如果下不了的话直接用以下网盘的方式下载
991 0
SpringBoot配置Druid数据库连接池
|
SQL Java 数据库连接
SpringDataJpa:JpaRepository增删改查
SpringDataJpa:JpaRepository增删改查
SpringDataJpa:JpaRepository增删改查
|
3天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8089 2
|
12天前
|
域名解析 人工智能 Linux
|
20天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10519 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
6天前
|
人工智能 安全 网络安全
|
11天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1581 5