关于JPA中使用原生SQL语句

本文介绍了一个使用Spring框架和JPA实现的Java类,该类提供了两个方法:一是通过课程ID查找教师姓名;二是通过课程ID查找学生列表。文章展示了如何利用EntityManager进行原生SQL查询,并通过事务管理确保数据的一致性和完整性。

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

import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import java.util.*;
import javax.persistence.*;

public class CustomerCourseDAO extends JpaDaoSupport implements ICustomerCourseDAO {

public String findTeacherNameByCourseId(Integer courseid) {
        String sql = "select concat(c.Given_Name,' ',c.Family_Name) as teachername from customer c,customer_course cc"
                + " where c.Customer_ID = cc.Customer_ID and cc.Related_Code = 2 and  cc.Course_ID = " + courseid.intValue();
        try {
            EntityManagerFactory emf = getJpaTemplate().getEntityManagerFactory();
            EntityManager newEm = emf.createEntityManager();
            EntityTransaction newTx = newEm.getTransaction();
            newTx.begin();

            List result = newEm.createNativeQuery(sql).getResultList();
            String teachername = "";
            if(result.size()==1){
                teachername = (String)result.get(0);
            }
            newEm.getDelegate();
            newTx.commit();
            newEm.close();
            emf.close();
           
            return teachername;
        } catch (RuntimeException re) {
            logger.error("find Teacher's Name by courseId failed", re);

            throw re;
        }
    }

 
    //add by edwin, 2007-11-08 测试通过
    @SuppressWarnings(value = "unchecked")
    public List<CustomerCourse> findTeaStuByCourseId(Integer id) {
        String sql = "select model.*  from  customer_course model " + "where model.Related_Code = 1 and model.Course_ID = " + id.intValue();

        try {
            EntityManagerFactory emf = getJpaTemplate().getEntityManagerFactory();
            EntityManager newEm = emf.createEntityManager();
            EntityTransaction newTx = newEm.getTransaction();
            newTx.begin();

            @SuppressWarnings(value = "unchecked")
            List<CustomerCourse> stu = newEm.createNativeQuery(sql,CustomerCourse.class).getResultList();
            newTx.commit();
            newEm.close();
            emf.close();
           
            return stu;
        } catch (RuntimeException re) {
            logger.error("find Teacher's students by courseId failed", re);

            throw re;
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值