jpa复合主键的使用 【转载】

文章出处:jpa复合主键的使用


AirLinePk复合主键类

package com.ljq.entity;

import javax.persistence.Column;
import javax.persistence.Embeddable;

/**
 * 使用复合主键要满足的条件
 * 
 * 1、要实现序列化 2、提供默认的构造方法 3、实现hashCope
 * 
 * @author Administrator
 * 
 */

@SuppressWarnings("serial")
@Embeddable  //embeddable: 可嵌入的
public class AirLinePk implements java.io.Serializable {
    @Column(length = 3)
    private String startCity;// 出发城市

    @Column(length = 3)
    private String endCity;// 抵达城市

    public AirLinePk() {
        super();
    }

    public AirLinePk(String startCity, String endCity) {
        super();
        this.startCity = startCity;
        this.endCity = endCity;
    }

    public String getEndCity() {
        return endCity;
    }

    public void setEndCity(String endCity) {
        this.endCity = endCity;
    }

    public String getStartCity() {
        return startCity;
    }

    public void setStartCity(String startCity) {
        this.startCity = startCity;
    }

    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = PRIME * result + ((endCity == null) ? 0 : endCity.hashCode());
        result = PRIME * result
                + ((startCity == null) ? 0 : startCity.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final AirLinePk other = (AirLinePk) obj;
        if (endCity == null) {
            if (other.endCity != null)
                return false;
        } else if (!endCity.equals(other.endCity))
            return false;
        if (startCity == null) {
            if (other.startCity != null)
                return false;
        } else if (!startCity.equals(other.startCity))
            return false;
        return true;
    }

}
AirLine实体类

package com.ljq.entity;


import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;

@SuppressWarnings("serial")
@Entity
public class AirLine implements java.io.Serializable{
    @EmbeddedId
    private AirLinePk id;
    
    @Column(length=20)
    private String name;

    public AirLine() {
        super();
    }

    public AirLine(String startCity,String endCity, String name) {
        this.id =new AirLinePk(startCity,endCity);
        this.name = name;
    }


    public AirLinePk getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    
    
    
}
PKTest测试类
package com.ljq.test;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.Test;

import com.ljq.entity.AirLine;
import com.ljq.entity.AirLinePk;

public class PKTest {

    @Test
    public void save() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("ljq");
        EntityManager em=factory.createEntityManager();
        em.getTransaction().begin();
        
        em.persist(new AirLine("PEK","SHA","北京飞上海"));
        
        
        em.getTransaction().commit();
        em.close();
        factory.close();
        
    }
    
    @Test
    public void find() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("ljq");
        EntityManager em=factory.createEntityManager();
        em.getTransaction().begin();
        
        AirLine airLine=em.find(AirLine.class, new AirLinePk("PEK","SHA"));
        System.out.println(airLine.getName());
        
        
        em.getTransaction().commit();
        em.close();
        factory.close();
        
    }
    
    @Test
    public void update() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("ljq");
        EntityManager em=factory.createEntityManager();
        em.getTransaction().begin();
        
        AirLine airLine=em.getReference(AirLine.class, new AirLinePk("PEK","SHA"));
        airLine.setName("北京飞上海北京飞上海");
        em.merge(airLine);
        
        
        em.getTransaction().commit();
        em.close();
        factory.close();
        
    }
    
    @SuppressWarnings({ "unused", "unchecked" })
    @Test
    public void list() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("ljq");
        EntityManager em=factory.createEntityManager();
        em.getTransaction().begin();
        
        
        List<AirLine> airLines=em.createQuery("select o from AirLine o").getResultList();
        for(AirLine air:airLines){
            System.out.println(air.getName());
        }
        
        em.getTransaction().commit();
        em.close();
        factory.close();
        
    }
    
    @SuppressWarnings({ "unused", "unchecked" })
    @Test
    public void detele() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("ljq");
        EntityManager em=factory.createEntityManager();
        em.getTransaction().begin();
        
        
        em.remove(em.getReference(AirLine.class, new AirLinePk("PEK","SHA")));
        
        em.getTransaction().commit();
        em.close();
        factory.close();
        
    }

    /**
     * 用来判断映射是否成功
     * 
     */
    @Test
    public void test() {
        Persistence.createEntityManagerFactory("ljq");
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用JPA复合查询来获取一个实体对象的列表。首先,确保你的实体类中定义了一个复合。然后,使用`@EmbeddedId`注解将复合嵌入到实体类中。 下面是一个示例,假设你有一个名为`User`的实体类,它具有复合`userId`和`companyId`: ```java @Entity public class User { @EmbeddedId private UserId id; // 其他属性和方法... } ``` 接下来,你需要创建一个表示复合的嵌入式类。在这个例子中,我将它命名为`UserId`: ```java @Embeddable public class UserId implements Serializable { private Long userId; private Long companyId; // 构造函数、getter和setter方法... } ``` 现在,你可以使用JPA的`EntityManager`或`JpaRepository`来进行查询。以下是一个使用`JpaRepository`的示例代码: ```java @Repository public interface UserRepository extends JpaRepository<User, UserId> { List<User> findAllByCompanyId(Long companyId); } ``` 在上面的示例中,我们定义了一个名为`UserRepository`的接口,并继承了`JpaRepository<User, UserId>`。通过添加名称为`findAllByCompanyId`的方法,你可以按照公司ID来查询匹配的用户列表。 现在,你可以在需要的地方注入`UserRepository`并调用`findAllByCompanyId`方法来获取相应的用户列表: ```java @Autowired private UserRepository userRepository; public List<User> getUsersByCompanyId(Long companyId) { return userRepository.findAllByCompanyId(companyId); } ``` 这样,你就可以使用JPA复合查询来获取用户列表了。记得根据你的实际情况进行适当的调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值