我正在做一个学校项目,但在连接表时遇到了麻烦,因此我可以使用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();

}


我希望我很清楚。预先感谢大家。

最佳答案

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

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

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

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

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

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

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

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

顺便说一句,对不起,英语不好。

关于java - JPA联接表查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55087642/

10-10 18:34
查看更多