實體類(JavaBean)一般都是和數據庫中的表結構一一對應


實體類(JavaBean)一般都是和數據庫中的表結構一一對應

本節希望實現的是,一個java類,能和數據庫對應上,然后操作數據庫。

實體類

JavaBean有特定的寫法

  • 必須要有一個無慘構造

  • 屬性必須私有化

  • 必須有對應的get/set方法

一般用來和數據庫的字段做映射 ORM

ORM:對象關系映射

  • 表--->類

  • 字段--->屬性

  • 行記錄--->對象

id name age address
1 桐人 22 日本
2 亞絲娜 22 日本
3 愛麗絲 22 日本
class People{
   private int id;
   private String name;
   private int age;
   private String name;
}

class A{
   new People(1,"桐人",22,"日本");
}

一般建package的時候,常用entity、pojo、vo、dto或者pojo來代表實體類文件夾

1、寫class

 

 

 1 package com.wang.dto;
 2 
 3 public class People {
 4     private int id;
 5     private String name;
 6     private int age;
 7     private String address;
 8 
 9     public People() {
10     }
11 
12     public People(int id, String name, int age, String address) {
13         this.id = id;
14         this.name = name;
15         this.age = age;
16         this.address = address;
17     }
18 
19     public int getId() {
20         return id;
21     }
22     public void setId(int id) {
23         this.id = id;
24     }
25 
26     public String getName() {
27         return name;
28     }
29 
30     public void setName(String name) {
31         this.name = name;
32     }
33 
34     public int getAge() {
35         return age;
36     }
37 
38     public void setAge(int age) {
39         this.age = age;
40     }
41 
42     public String getAddress() {
43         return address;
44     }
45 
46     public void setAddress(String address) {
47         this.address = address;
48     }
49     @Override
50     public String toString() {
51         return "People{" +
52                 "id=" + id +
53                 ", name='" + name + '\'' +
54                 ", age=" + age +
55                 ", address='" + address + '\'' +
56                 '}';
57     }
58 }
View Code

2、建數據庫

新建名為jdbc的數據庫,新建名為people的表

 

3、JDBC連接數據庫

實體類一般都是和數據庫中的表結構一一對應。

上面寫的Java類的People類,和這個people一一對應。

4、新建javabean.jsp

 1 <%@ page import="com.wang.dto.People" %>
 2 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 3 <html>
 4 <head>
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 
 9 <%
10     People people = new People();
11     people.setId(3);
12     people.setName("wangzan");
13     people.setAge(26);
14     people.setAddress("beijing");
15 %>
16 
17 
18 <%=people.getId()%>
19 <%=people.getName()%>
20 <%=people.getAge()%>
21 <%=people.getAddress()%>
22 </body>
23 </html>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM