溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用Jorm增刪查改數(shù)據(jù)庫(kù)

發(fā)布時(shí)間:2021-09-15 11:49:02 來源:億速云 閱讀:115 作者:chen 欄目:數(shù)據(jù)庫(kù)

這篇文章主要介紹“如何使用Jorm增刪查改數(shù)據(jù)庫(kù)”,在日常操作中,相信很多人在如何使用Jorm增刪查改數(shù)據(jù)庫(kù)問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”如何使用Jorm增刪查改數(shù)據(jù)庫(kù)”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

> 準(zhǔn)備
MySQL為例,執(zhí)行下面的sql建立數(shù)據(jù)表
CREATE TABLE `t_user` (               
        `id` int(11) NOT NULL,              
        `name` varchar(50) DEFAULT NULL,    
        `sex` char(4) DEFAULT NULL,         
        `age` int(11) DEFAULT NULL,         
        `career` varchar(100) DEFAULT NULL, 
        PRIMARY KEY (`id`)                  
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

> 引入jar或maven依賴,需要jar包
gerald-jorm-1.0.5.jar 最新版本下載:
commons-logging-1.1.1.jar
log4j-1.2.14.jar
mysql-connector-java-5.1.6.jar
javassist-3.11.0.GA.jar 或 cglib-nodep-2.2.2.jar (根據(jù)實(shí)際情況選擇性加入)


> 配置文件
在你的java工程的classpath下建立config.properties和jdbc.cfg.xml文件
config.properties內(nèi)容:
# 下面路徑可以根據(jù)實(shí)際情況指定,為相對(duì)classpath的路徑地址
jdbc.config.path=jdbc.cfg.xml

jdbc.cfg.xml內(nèi)容:
<?xml version='1.0' encoding="UTF-8"?>
<jdbc-configuration>

  <constant name="show_sql" value="true" />
  <constant name="jdbc.batch_size" value="600" />
  <constant name="bytecode.provider" value="cglib" />
 
  <connections default="simple">
 
    <connection name="simple">
      <property name="connection.implementation">org.javaclub.jorm.jdbc.connection.impl.SimpleConnection</property>
      <property name="connection.dialect">MySQLDialect</property>
      <property name="connection.driver">com.mysql.jdbc.Driver</property>
      <property name="connection.jdbcurl">jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=UTF-8</property>
      <property name="connection.database">test</property>
      <property name="connection.username">root</property>
      <property name="connection.password">root</property>
    </connection>

    <connection name="c3p0">
      <property name="connection.implementation">org.javaclub.jorm.jdbc.connection.impl.PooledConnection</property>
      <property name="connection.dialect">MySQLDialect</property>
      <property name="connection.driver">com.mysql.jdbc.Driver</property>
      <property name="connection.jdbcurl">jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=UTF-8</property>
      <property name="connection.database">test</property>
      <property name="connection.username">root</property>
      <property name="connection.password">root</property>
      <property name="connection.pool.min">1</property>
      <property name="connection.pool.max">8</property>
      <property name="connection.test.sql">select 1</property>
    </connection>
   
  </connections>

</jdbc-configuration>


> 實(shí)體類User.java
@PK(value = "id")
@Entity(table="t_user")
public class User {
   
    @Id
    private int id;

    private String name;

    private String sex;

    private Integer age;

    private String career;
   
    @NoColumn
    private int kvalue;
   
    public User() {
        super();
    }

    public User(String name, String sex, Integer age, String career) {
        super();
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.career = career;
    }

    public User(Integer id, String name, String sex, Integer age, String career) {
        super();
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.career = career;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCareer() {
        return career;
    }

    public void setCareer(String career) {
        this.career = career;
    }

    public int getKvalue() {
        return kvalue;
    }

    public void setKvalue(int kvalue) {
        this.kvalue = kvalue;
    }

    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("[" + id + ", " + name + ", " + sex + ", " + age + ", " + career + "]");
        return sb.toString();
    }

}

這里字段和java實(shí)體類User的屬性在命名上是一致的,如果不一致,比如如果表創(chuàng)建sql為:
CREATE TABLE `t_user` (               
        `user_id` int(11) NOT NULL,              
        `user_name` varchar(50) DEFAULT NULL,    
        `sex` char(4) DEFAULT NULL,         
        `col_age` int(11) DEFAULT NULL,         
        `career_job` varchar(100) DEFAULT NULL, 
        PRIMARY KEY (`id`)                  
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

那么對(duì)應(yīng)的實(shí)體User應(yīng)該寫成:
@PK(value = "id")
@Entity(table="t_user")
public class User {
   
    @Id
    @Column("user_id")
    private int id;

    @Column("user_name")
    private String name;
       
    // 與數(shù)據(jù)庫(kù)字段命名一致,可以不指定@Column
    private String sex;

    @Column("col_age")
    private Integer age;

    @Column("career_job")
    private String career;
   
    @NoColumn
    private int kvalue;
   
    public User() {
        super();
    }

    public User(String name, String sex, Integer age, String career) {
        super();
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.career = career;
    }

    public User(Integer id, String name, String sex, Integer age, String career) {
        super();
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.career = career;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCareer() {
        return career;
    }

    public void setCareer(String career) {
        this.career = career;
    }

    public int getKvalue() {
        return kvalue;
    }

    public void setKvalue(int kvalue) {
        this.kvalue = kvalue;
    }

    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("[" + id + ", " + name + ", " + sex + ", " + age + ", " + career + "]");
        return sb.toString();
    }

}


> 對(duì)User的增刪查改,UserCrudTest.java,記得引入junit-4.8.2.jar
public class UserCrudTest {

    static Session session;
   
    @BeforeClass
    public static void before() {
        session = Jorm.getSession();
    }
   
    @AfterClass
    public static void after() {
        Jorm.free();
    }
   
    @Test
    public void save_user() {
        session.clean(User.class);
        User user = null;
        for (int i = 0; i < 600; i++) {
            String sex = (i % 2 == 0 ? "男" : "女");
            user = new User(Strings.fixed(5), sex, Numbers.random(98), Strings.random(8));
            session.save(user);
        }
    }
   
    @Test // 批量保存
    public void batch_save_user() {
        session.clean(User.class);
        JdbcBatcher batcher = session.createBatcher();
        User user = null;
        for (int i = 0; i < 600; i++) {
            String sex = (i % 2 == 0 ? "男" : "女");
            user = new User(Strings.fixed(5), sex, Numbers.random(98), Strings.random(8));
            batcher.save(user);
        }
        batcher.execute();
    }
   
    @Test
    public void loadUser() {
        User user = session.read(User.class, 1);
        // 這里user是一個(gè)代理對(duì)象,因?yàn)锧Entity(table="t_user", lazy = true)
        System.out.println(user.getCareer());// 發(fā)出查詢sql
    }
   
    @Test
    public void deletUser() {
        User user = session.read(User.class, 1);
        if(null != user) {
            session.delete(user);
        }
        user = session.read(User.class, 1);
        System.out.println(user);
    }
   
    @Test
    public void test_update_proxy() {
       
        User u;
        u = session.read(User.class, 2);
        Assert.assertNotNull(u);
        Assert.assertTrue(u instanceof JormProxy);
       
        u.setName("Gerald.Chen");
        session.update(u);
        System.out.println(u.getName());
        u = session.read(User.class, 2);
        Assert.assertTrue("Gerald.Chen".equals(u.getName()));
    }
   
    @Test
    public void queryUser() {
        SqlParams<User> params = new SqlParams<User>();
        params.setObjectClass(User.class);
        params.setFirstResult(8);
        params.setMaxResults(20);
        List<User> users = session.list(params);
        System.out.println(users.size());
        System.out.println(users);
    }
   
}


到此,關(guān)于“如何使用Jorm增刪查改數(shù)據(jù)庫(kù)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI