JFinal getModel方法(從頁面表單中獲取Model對象)+數(shù)據(jù)庫存儲問題
一、getmodel方法
1.在JConfig配置類中的數(shù)據(jù)庫映射(存儲到數(shù)據(jù)庫時需要此配置)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public void configPlugin(Plugins me) { C3p0Plugin cp = null ; try { cp = new C3p0Plugin( "jdbc:mysql://localhost:3306/huaxuetang?useUnicode=true&characterEncoding=utf-8" , "root" , "1234" ); System.out.println( "成功" ); } catch (Exception e) { System.out.println( "連接失敗" ); } me.add(cp); ActiveRecordPlugin arp = new ActiveRecordPlugin(cp); arp.setShowSql( true ); me.add(arp); arp.addMapping( "bse_user" , "id" , User. class ); arp.addMapping( "grade_one_choice" , "id" ,GOneQuestion. class ); } |
中arp。addMapping()中有三個參數(shù),第一個是數(shù)據(jù)庫表名,第二個主鍵,第三個是對應(yīng)的Model類名稱
2.Model類
1
2
3
4
5
6
7
|
import com.jfinal.plugin.activerecord.Model; public class GOneQuestion extends Model<GOneQuestion>{ private static final long serialVersionUID = 1L; // 聲明一個全局操作的變量 public final static GOneQuestion questiondao = new GOneQuestion(); } |
3.前端表單
1
|
< input type = "text" name = "gOneQuestion.A" class = "required" maxlength = "50" style = "width: 250px" /> |
前端中的name=“Modelname.atrrname”意思:比如此例中的model為GOneQuestion,表單中的屬性為A,所以name就為:gOneQuestion.A
注意:只有首字母變成小寫,其他不變
4.getmodel獲取
1
|
GOneQuestion question =getModel(GOneQuestion. class ); |
二、數(shù)據(jù)庫存儲問題
jfianl說明文檔中:
User 中定義的 public static final User dao 對象是全局共享的,只能用于數(shù)據(jù)庫查詢, 不能用于數(shù)據(jù)承載對象。數(shù)據(jù)承載需要使用 new User().set(…)來實(shí)現(xiàn)。
意思是:比如本例中model定義的questiondao只能用來查詢,不能用來插入數(shù)據(jù)。
插入數(shù)據(jù)時:(使用錯會出現(xiàn)主鍵重復(fù)問題)
1
2
3
|
new GOneQuestion() .set( "book" , question.getStr( "book" )) .save(); |
刪除增加數(shù)據(jù)時:GOneQuestion.questiondao.方法名