1.去ormlite官网下载这两个jar包;
2.导入到你的项目中;
3,编写实体bean,并且和数据库中对应的表对应【切记,使用该框架时,实体bean必须要有一个显式的无参构造方法】
【实体类和表对应】
package hyi.bean;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName= "account")
public class Account {
@DatabaseField(id= true,generatedId= true)
private String name;
@DatabaseField(columnName= "password")
private String password;
//使用该框架,实体类必须要有一个无参数构造方法
public Account(){}
public Account(String name,String password){
this.name=name;
this.password=password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
【使用ormlite框架,存取数据】
package hyi.dao;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import hyi.bean.Account;
import java.sql.SQLException;
public class AccountDao {
public static void main(String[] args) {
ConnectionSource connectionSource = null;
try {
//1.获取JDBC数据库连接
connectionSource = new JdbcConnectionSource("指定数据库链接地址");
//2.创建实体类对应的dao【参数为数据库连接对象,和对应的实体类class对象】
Dao<Account,String> accountDao = DaoManager.createDao(connectionSource, Account.class);
//3.使用ormlite提供的【表工具】建表
TableUtils.createTable(connectionSource,Account.class);
// a.新建一条数据记录
Account account=new Account();
account.setName("张三");
//b.使用对应dao增加这条记录
accountDao.create(account);
//c.使用dao根据ID查询出对应的记录对象
Account account1=accountDao.queryForId("张三");
//d.关闭数据库连接,关闭资源
connectionSource.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}