【Java Web开发学习】Spring JPA

本文详细介绍了在JavaWeb开发中如何使用Spring JPA进行数据库操作,包括配置JNDI数据源、声明LocalContainerEntityManagerFactoryBean、编写Repository等步骤。通过具体代码示例,展示了如何实现数据的增删改查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【Java Web开发学习】Spring JPA

 转载:https://www.cnblogs.com/yangchongxing/p/10082864.html

 

1、使用容器管理类型的JPA

JNDI数据源

package cn.ycx.config;

import javax.naming.NamingException;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.jndi.JndiObjectFactoryBean;

public class DataSourceConfig {
    @Bean
    public DataSource dataSource() throws IllegalArgumentException, NamingException {
        System.out.println("dataSource...");
        JndiObjectFactoryBean jndi = new JndiObjectFactoryBean();
        jndi.setJndiName("jdbc/mysql");
        jndi.setResourceRef(true);//自动添加 java:comp/env/ 前缀
        jndi.setProxyInterface(javax.sql.DataSource.class);
        jndi.afterPropertiesSet();
        return (DataSource) jndi.getObject();
    }    
}

声明LocalContainerEntityManagerFactoryBean

package cn.ycx.config;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

@Configuration
@ComponentScan(basePackages = {"cn.ycx"}, excludeFilters = {
        @Filter( type=FilterType.ANNOTATION, value=org.springframework.stereotype.Controller.class)
        })
@Import(DataSourceConfig.class)
public class RootConfig {
    @Bean
    public MultipartResolver multipartResolver() {
        System.out.println("multipartResolver...");
        return new StandardServletMultipartResolver();
    }
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        System.out.println("jdbcTemplate...");
        return new JdbcTemplate(dataSource);
    }
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        System.out.println("jpaVendorAdapter...");
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setDatabase(Database.MYSQL);
        adapter.setShowSql(true);
        adapter.setGenerateDdl(false);
        adapter.setDatabasePlatform("org.hibernate.dialect.MySQL55Dialect");
        return adapter;
    }
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter ) {
        System.out.println("localContainerEntityManagerFactoryBean...");
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource);
        emfb.setJpaVendorAdapter(jpaVendorAdapter);
        emfb.setPackagesToScan("cn.ycx.entity");
        return emfb;
    }
}

编写Repository

package cn.ycx.dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.ycx.entity.User;

@Repository
public class IndexDao {
    @Autowired
    private JdbcOperations jdbcOperations;
    @PersistenceUnit
    private EntityManagerFactory emf;
    
    public void addUser() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        User user = new User();
        user.setId(format.format(new Date()));
        user.setUsername("name");
        EntityManager em = emf.createEntityManager();
        EntityTransaction et = em.getTransaction();
        et.begin();//开始事务
        em.persist(user);
        et.commit();//提交事务
    }
    public Object insert() {
        int count = jdbcOperations.update("insert into user(id,username,password)values(?,?,?)","2","user","user");
        Map<String, String> data = new HashMap<String, String>();
        data.put("count", String.valueOf(count));
        return data;
    }
    public Object update() {
        int count = jdbcOperations.update("update user set username=?, password=? where id=?","admin","admin","1");
        Map<String, String> data = new HashMap<String, String>();
        data.put("count", String.valueOf(count));
        return data;
    }
}

 

转载于:https://www.cnblogs.com/yangchongxing/p/10082864.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值