spring注解整合JPA的实现

目录结构如下:
spring注解整合JPA的实现_第1张图片
TesetSpringJpa.java内容:

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import repository.UserDao;

import java.util.Arrays;

public class TesetSpringJpa {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(ApplicationCongfigura.class);
        String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
        Arrays.asList(beanDefinitionNames).forEach(x-> System.out.println(x));
        UserDao userDao = annotationConfigApplicationContext.getBean(UserDao.class);
        System.out.println(userDao.findAll());
    }
}

这里的Arrays.aslist只是用于测试并无实际的用处,此处可能会报错,编译版本需要在1.8及以上,如在1.8一下则可以将Arrays.asList这段代码注释掉。
ApplicationCongfigura类:

import com.mchange.v2.c3p0.ComboPooledDataSource;
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.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableJpaRepositories(basePackages = "repository")  // 开启JPARepositories basePackages = 你的dao层的包名
@EnableTransactionManagement(proxyTargetClass = true) //  开启注解式事务管理
public class ApplicationCongfigura {
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver"); // 这里使用的mysql版本比较高所以使用如下这个类,也可以使用原来的包
        dataSource.setJdbcUrl("jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");// url
        dataSource.setUser("root"); // 用户名
        dataSource.setPassword("123456"); // 密码
        return dataSource;
    }
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws PropertyVetoException {
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        localContainerEntityManagerFactoryBean.setDataSource(dataSource());
        localContainerEntityManagerFactoryBean.setPackagesToScan("domain"); // 实体类管理工厂管理者需要扫描的entity的包名,此处的entity在domain
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        localContainerEntityManagerFactoryBean.setJpaVendorAdapter(adapter);
        Map map = new HashMap<>();
        map.put("hibernate.show_sql",true);
        map.put("hibernate.hbm2ddl.auto","update");
        map.put("hibernate.format_sql",true);
        localContainerEntityManagerFactoryBean.setJpaPropertyMap(map);
        return localContainerEntityManagerFactoryBean;
    }
    @Bean
    public JpaTransactionManager transactionManager() throws PropertyVetoException {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }
}

UserDao类:

package repository;

import domain.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository {
}

User类:

package domain;

import javax.persistence.*;

@Entity
@Table(name = "t_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "username")
    private String userName;

    @Column(name = "password")
    private String passWord;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
}

pom内容:


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.springgroupId>
    <artifactId>jpa-demoartifactId>
    <version>1.0-SNAPSHOTversion>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.1.7.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-ormartifactId>
            <version>5.1.7.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.springframework.datagroupId>
            <artifactId>spring-data-jpaartifactId>
            <version>2.1.6.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-coreartifactId>
            <version>5.4.2.Finalversion>
        dependency>

        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-entitymanagerartifactId>
            <version>5.4.2.Finalversion>
        dependency>

        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.2version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.16version>
        dependency>
    dependencies>
project>

表内容预览:
spring注解整合JPA的实现_第2张图片
最后附上成功图:
在这里插入图片描述
留个demo 下载地址吧:
demo

你可能感兴趣的:(java工作记录)