tell me how to link 2 tables correctly, and display them in JSP.

@Entity @Table(name = "clients") public class Clients implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "clientsid") private Long clientsid; @Column(name = "name") private String name; @Column(name = "surname") private String surname; @Column(name = "patronymic") private String patronymic; @OneToOne @JoinColumn(name="phonesid") private Phones phonesid; 

I can not understand how to properly upload to the page.

 @Entity @Table(name = "phones") public class Phones implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "phonesid") private Long phonesid; @Column(name = "number") private String number; @Column(name = "type") private String type; @Column(name = "commetns") private String comments; 
  • Are these customers and their phones? Does each client have only one telephone? - Mikhail Vaysman
  • yes right @Mikhail Vaysman - Verlamov
  • you just have classes in plural. it is confusing. on the page you bring one client? - Mikhail Vaysman
  • right now, thanks a little, I’ve got it done))) yes, I’m bringing one client with his phone number. @Mikhail Vaysman - Verlamov

1 answer 1

It may be that my code is not the best and adequate))
Suppose your Entity is:

 import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "clients", catalog = "mybase") public class Clients implements Serializable{ @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "clientsid") private Long clientsid; @Column(name = "name") private String name; @Column(name = "surname") private String surname; @Column(name = "patronymic") private String patronymic; @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="phonesid") private Phones phones; public Clients() { } public Long getClientsid() { return clientsid; } public void setClientsid(Long clientsid) { this.clientsid = clientsid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getPatronymic() { return patronymic; } public void setPatronymic(String patronymic) { this.patronymic = patronymic; } public Phones getPhones() { return phones; } public void setPhones(Phones phones) { this.phones = phones; } } 

and

 import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "phones", catalog = "mybase") public class Phones implements Serializable{ @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "phonesid") private Long phonesid; @Column(name = "number") private String number; @Column(name = "type") private String type; @Column(name = "commetns") private String comments; public Phones() { } public Long getPhonesid() { return phonesid; } public void setPhonesid(Long phonesid) { this.phonesid = phonesid; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } } 

FILE hibernate.cfg.xml

 <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mybase?serverTimezone=UTC</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <!--<property name="hibernate.hbm2ddl.auto">create</property>--> <mapping class="Entity.Clients" /> <mapping class="Entity.Phones" /> </session-factory> </hibernate-configuration> 

pom.xml can be like this

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>stackoverflowHIBERNATE</groupId> <artifactId>stackoverflowHIBERNATE</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>stackoverflowHIBERNATE Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <hibernate.version>5.2.2.Final</hibernate.version> </properties> <dependencies> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>stackoverflowHIBERNATE</finalName> </build> </project> 

A simple DAO with one method - pull out all Clients from the database. We will use this class in a servlet (for more information, click here )

 public class DaoClient { private static SessionFactory factory; public List<Clients> getAllClients() { try{ factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } Session session = factory.openSession(); Transaction transaction = null; List<Clients> clientses = new ArrayList<Clients>(); try{ transaction = session.beginTransaction(); clientses = (List<Clients>) session.createQuery("FROM Clients").list(); transaction.commit(); }catch (HibernateException e) { if (transaction!=null) transaction.rollback(); e.printStackTrace(); }finally { session.close(); } return clientses; } } 

Servlet

 @WebServlet("/base") public class SourceServlet extends HttpServlet { DaoClient daoClient = new DaoClient(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Clients> clientses = daoClient.getAllClients(); request.setAttribute("Clients", clientses); request.getRequestDispatcher("base.jsp").forward(request, response); } } 

And JSP itself: (if you want to implement the "full cycle" of creating Clients from JSP and so on, you can get acquainted with this video )

 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>Base</title> </head> <body> <c:if test="${!empty Clients}"> <table> <tr> <th>Name</th> <th>Surname</th> <th>Phone</th> </tr> <c:forEach items="${Clients}" var="clients"> <tr> <td>${clients.name}</td> <td>${clients.surname}</td> <td>${clients.phones.number}</td> </tr> </c:forEach> </table> </c:if> </body> </html> 

Project structure
Structure


Test.java was needed only for insert in the database

 import Entity.Clients; import Entity.Phones; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class Test { private static SessionFactory factory; public static void main(String[] args) { Phones phones1 = new Phones(); phones1.setNumber("911"); phones1.setComments("Call me!"); phones1.setType("MyType1"); Phones phones2 = new Phones(); phones2.setNumber("88005553535"); phones2.setComments("don't forget"); phones2.setType("ClassicType"); Clients clients1 = new Clients(); clients1.setName("Ivan"); clients1.setSurname("Ivanov"); clients1.setPatronymic("Pertovich"); clients1.setPhones(phones1); Clients clients2 = new Clients(); clients2.setName("Vladimir"); clients2.setSurname("Kapustin"); clients2.setPatronymic("Romanovich"); clients2.setPhones(phones2); try{ factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); session.save(clients1); session.save(clients2); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } } 

web.xml default

 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> </web-app> 

and more about hibernate.cfg.xml Suppose the base in it is indicated as

 <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mybase</property> 

But the tables are missing there. Then remove comments from the line

 <property name="hibernate.hbm2ddl.auto">create</property> 

This row will automatically create the tables when the first insert is based on the annotated classes Clients and Phones. The main thing after this automatic table creation is to back-comment the line or delete it. Otherwise, each "restart" will reset the base.


The result will be as follows:
enter image description here

  • @CheshereK Thanks for the example. It does not start ((I will look further. - Verlamov
  • Now add the answer, show the structure of the project. Suddenly, somewhere we did not understand a friend of the friend) - CheshireK
  • @CheshieK In general, I understand everything. we will assume that the answer is correct))) the project does not start ((((HTTP Status 500 - Error instantiating servlet class com.testapp.servlet.SourceServlet - Verlamov
  • @Verlamov I do not know the structure of your project. I can only assume this: remove the line @WebServlet("/base") from the servlet and manually register in the web.xml servlet <servlet> <servlet-name>sourceServlet</servlet-name> <servlet-class>com.testapp.servlet.SourceServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>sourceServlet</servlet-name> <url-pattern>/base</url-pattern> </servlet-mapping> - CheshireK