JPA联接表查询

时间:2019-03-10 12:23:53

标签: java mysql hibernate jpa

我正在做一个学校项目,我在连接表时遇到麻烦,因此我可以使用JSTL在JSP文件中显示输出。我将提供所有必要的代码。我知道我需要以某种方式连接实体,但我不知道如何。

SQL:

CREATE TABLE IF NOT EXISTS `totelegram`.`contacts` (
`id` INT NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
`last_name` VARCHAR(45) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
`phone_number` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC),
UNIQUE INDEX `phone_number_UNIQUE` (`phone_number` ASC))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `totelegram`.`messages` (
`id_message` INT NOT NULL AUTO_INCREMENT,
`message` VARCHAR(2000) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT 
NULL,
`time` VARCHAR(45) NOT NULL,
`contacts_id` INT NOT NULL,
 PRIMARY KEY (`id_message`),
 UNIQUE INDEX `id_message_UNIQUE` (`id_message` ASC),
 INDEX `fk_messages_contacts_idx` (`contacts_id` ASC),
 CONSTRAINT `fk_messages_contacts`
 FOREIGN KEY (`contacts_id`)
 REFERENCES `totelegram`.`contacts` (`id`)
 ON DELETE NO ACTION
 ON UPDATE NO ACTION)
 ENGINE = InnoDB;

Contacts.java

@Entity(name = "contacts")
public class Contacts implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

@javax.persistence.Column(name = "first_name")
private String firstName;

@javax.persistence.Column(name = "last_name")
private String lastName;

@javax.persistence.Column(name = "phone_number")
private String phoneNumber;

...getters/setters, constructor, toString...

Messages.java

@Entity(name = "messages")
public class Messages implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@javax.persistence.Column(name = "id_message")
private int id;

private String message;

private String time;

@javax.persistence.Column(name = "contacts_id")
private int contactsId;

...getters/setters, constructor, toString...

MessagesRepository.java

public interface MessagesRepository extends JpaRepository<Messages, Integer> {

//custom query which will output this
//SELECT b.message, b.time, b.contacts_id, a.first_name, a.last_name FROM messages AS b INNER JOIN contacts as A ON (b.contacts_id=a.id) ORDER BY time ASC;
public List<Messages> findAll(); 

}

我希望我很清楚。谢谢大家。

1 个答案:

答案 0 :(得分:0)

据我了解,一个联系人可以有N条消息,没有联系人就不能有消息,对吧?

由于类之间存在关系,因此必须在jpa中使用特定的注释,例如:

消息类中,您应该使用@ManyToOne批注,因为您有多个针对一个联系人的消息。 JoinColumn将在消息表中输入 contacts_id

@ManyToOne @JoinColumn(name = "contacts_id") private Contacts contact;

Contacts 类中,您应该使用@OneToMany批注,因为一个联系人有很多消息。 appedBy在消息类中作为联系人的引用。

@OneToMany(mappedBy = "contact") private List<Messages> messages = new ArrayList<>();

到目前为止,您已经在“联系人”和“消息”之间建立了双向引用。现在,在您的服务类别中,我建议您通过联系人找到消息,因为没有联系人就无法收到消息。这是一个存储库原则。

Contacts con = repository.findOne(1); con.getMessages();

顺便说一句,抱歉英语不好。