JFinal getModel方法(從頁(yè)面表單中獲取Model對(duì)象)+數(shù)據(jù)庫(kù)存儲(chǔ)問(wèn)題
一、getmodel方法
1.在JConfig配置類(lèi)中的數(shù)據(jù)庫(kù)映射(存儲(chǔ)到數(shù)據(jù)庫(kù)時(shí)需要此配置)
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()中有三個(gè)參數(shù),第一個(gè)是數(shù)據(jù)庫(kù)表名,第二個(gè)主鍵,第三個(gè)是對(duì)應(yīng)的Model類(lèi)名稱(chēng)
2.Model類(lèi)
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; // 聲明一個(gè)全局操作的變量 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
注意:只有首字母變成小寫(xiě),其他不變
4.getmodel獲取
1
|
GOneQuestion question =getModel(GOneQuestion. class ); |
二、數(shù)據(jù)庫(kù)存儲(chǔ)問(wèn)題
jfianl說(shuō)明文檔中:
User 中定義的 public static final User dao 對(duì)象是全局共享的,只能用于數(shù)據(jù)庫(kù)查詢(xún), 不能用于數(shù)據(jù)承載對(duì)象。數(shù)據(jù)承載需要使用 new User().set(…)來(lái)實(shí)現(xiàn)。
意思是:比如本例中model定義的questiondao只能用來(lái)查詢(xún),不能用來(lái)插入數(shù)據(jù)。
插入數(shù)據(jù)時(shí):(使用錯(cuò)會(huì)出現(xiàn)主鍵重復(fù)問(wèn)題)
1
2
3
|
new GOneQuestion() .set( "book" , question.getStr( "book" )) .save(); |
刪除增加數(shù)據(jù)時(shí):GOneQuestion.questiondao.方法名