android對象關係映射框架ormlite學習之單表操作

總感覺用原始的SQLLiteHelper操作數據庫有點麻煩,上網找了些android數據庫orm框架,對比了一下,現在使用ormlite的人貌似挺多的,在網上找了ormlite官方文檔,根據官方文檔,今天寫了個demo,主要是用戶註冊,用戶信息查看以及刪除,運行效果如圖:以前也用過一個同樣的orm框架Afinal,但是感覺Afinal沒有ormlite之強大。


Ormlite官網:http://ormlite.com/     開發文檔下載(pdf)。 但是是英文文檔哦,不要一看到是英文的就害怕了,其實裏面單詞比較簡單,能夠看得懂的,多看看英文文檔還是挺有幫助的。

一:要使用ormlite很簡單,只需要下載相應的兩個jar包(目前最新的jar包ormlite-android-4.48.jar,ormlite-core-4.48.jar下載)並導入工程即可。

二:創建實體類

@DatabaseTable(tableName = "tb_user")
//如果沒有特別指出tableName = "tb_user",那麼默認情況將類名作爲表名
//這裏也可以使用註解@Entity,因爲ORMLite既支持它自己的註解(@DatabaseTable和 @DatabaseField)也支持很多來自javax.persistence包中標準的註解。
//你可以使用來自javax.persistence包的更多的標準JPA註解。
public class User {
	//用戶編號
	/**
	 * id:這個字段是否爲主鍵,默認爲false
	 * generatedId:字段是否自動增加。默認爲false。
	 * 注意:id和generatedId只能指明一個,否則會報錯的
	 */
	//可以用javax.persistence註解: @Id,@Column
	@DatabaseField(generatedId=true)
	private int userId;
	//用戶名
	@DatabaseField
	private String userName;
	//密碼
	@DatabaseField
	private String password;
	
	public User() {
		//必須提供無參構造函數,這樣查詢的時候可以返回查詢出來的對象
	}
	public User( int userId,String userName, String password) {
		this.userId = userId;
		this.userName = userName;
		this.password = password;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

三:創建SQLLiteOpenHelper,在這裏有兩個比較重要的類OrmLiteSqliteOpenHelper(當你的應用被加載時創建和更新數據庫以及爲其他的類提供DAO類,必須實現onCreate(SQLiteDatabasesqliteDatabase, ConnectionSource

connectionSource) and onUpgrade(SQLiteDatabasedatabase, ConnectionSource

connectionSource, intoldVersion, int newVersion).這兩個類),RuntimeExceptionDao(默認情況下,大多數的dao方法都會拋出SQLException,因爲SQLException是大部分jdbc以及其他的sql調用時拋出的默認異常。 但是在android平臺上,尤其是,絕大部分的異常繼承了RuntimeException,添加了一個RuntimeExceptionDao來封裝所有在運行時因調用底層dao方法所拋出的運行時異常。)

public class DatabaseHelper extends OrmLiteSqliteOpenHelper{
    // 數據庫名稱  
	private static final String DATABASE_NAME = "helloAndroid.db"; 
    // 數據庫version  
	private static final int DATABASE_VERSION = 1;
	
	/**
	 * 包含兩個泛型:
	 * 第一個泛型表DAO操作的類
	 * 第二個表示操作類的主鍵類型
	 */
	private Dao<User, Integer> userDao = null;
	
	private RuntimeExceptionDao<User, Integer> simpleRuntimeDao = null;
    
	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}
	
	@Override
	public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onCreate");
			TableUtils.createTable(connectionSource, User.class);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}
		
	}
	/**
	 * 插入一條數據
	 */
	public void insert(User user){
		RuntimeExceptionDao<User, Integer> dao = getSimpleDataDao();
		//通過實體對象創建在數據庫中創建一條數據,成功返回1,說明插入了一條數據
		Log.i("test", "dao = " + dao+"  user= "+user);
		int returnValue = dao.create(user);
		Log.i("test", "插入數據後返回值:"+returnValue);
	}
	/**
	 * 查詢所有的用戶信息
	 * @return
	 */
	public List<User> findAllUser(){
		RuntimeExceptionDao<User, Integer> dao = getSimpleDataDao();
		return dao.queryForAll();
	}
	/**
	 * 刪除第一條用戶信息
	 */
	public void deleteById(){
		RuntimeExceptionDao<User, Integer> dao = getSimpleDataDao();
		List<User> list = dao.queryForAll();
		//刪除成功返回1(刪除了一條數據)
		if(list.size()>0){
			int returnValue = dao.deleteById(list.get(0).getUserId());
			Log.i("test", "刪除一條數據後返回值:"+returnValue);
		}
		
	}
	/**
	 * 批量刪除用戶信息
	 */
	public void deleteByIds(){
		RuntimeExceptionDao<User, Integer> dao = getSimpleDataDao();
		List<User> list = dao.queryForAll();
		List<Integer> ids = new ArrayList<Integer>();
		if(list.size()>0){
			for(User u:list){
				ids.add(u.getUserId());
			}
			//返回刪除的記錄數
			int returnValue = dao.deleteIds(ids);
			Log.i("test", "批量刪除後返回值:"+returnValue);
		}
		
	}
	
	public RuntimeExceptionDao<User, Integer> getSimpleDataDao() {
		if (simpleRuntimeDao == null) {
			simpleRuntimeDao = getRuntimeExceptionDao(User.class);
		}
		Log.i("test", "simpleRuntimeDao ======= "+simpleRuntimeDao);
		return simpleRuntimeDao;
	}

	/**
	 * 這個方法在你的應用升級以及它有一個更高的版本號時調用。所以需要你調整各種數據來適應新的版本
	 */
	@Override
	public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVersion,
			int newVersion) {
		Log.i("test", "更新....");
		try {
			Log.i(DatabaseHelper.class.getName(), "onUpgrade");
			//刪掉舊版本的數據
			TableUtils.dropTable(connectionSource, User.class, true);
			//創建一個新的版本
			onCreate(sqliteDatabase, connectionSource);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
			throw new RuntimeException(e);
		}
	}
	
	public Dao<User, Integer> getDao() throws SQLException {
		if (userDao == null) {
			userDao = getDao(User.class);
		}
		return userDao;
	}
}

四:接下來就是Activity了。

MainActivity:當程序運行便進入該類,主要是顯示頁面的那幾個按鈕以及顯示查詢出來的用戶信息。

public class MainActivity extends Activity {

	Button button1;//註冊按鈕
	Button button2;//顯示按鈕
	Button button3;//刪除按鈕
	Button button4;//批量刪除按鈕
	TextView textView;//用來顯示查詢到的用戶信息
	DatabaseHelper helper = new DatabaseHelper(this);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		button1 = (Button)this.findViewById(R.id.main_btn_regist);
		button2 = (Button)this.findViewById(R.id.main_btn_show);
		button3 = (Button)this.findViewById(R.id.main_btn_delete);
		button4 = (Button)this.findViewById(R.id.main_btn_deleteAll);
		textView = (TextView)this.findViewById(R.id.main_show_user);
		//點擊註冊按鈕跳轉到註冊頁面
		button1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, RegistActivity.class);
				startActivity(intent);
			}
		});
		//點擊“顯示”按鈕跳轉到用戶信息顯示頁面並將註冊用戶信息顯示出來
		button2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				List<User> userList = helper.findAllUser();
				String str = "";
				if(userList.size()>0){
					//將查詢到的用戶信息顯示出來
					for(User user:userList){
						str+="用戶"+user.getUserId()+":"+user.getUserName()+"    密碼:"+user.getPassword();
					}
					textView.setText(str);
				}else{
					textView.setText("親!還沒註冊吧!");
				}
			}
		});
		//刪除一條記錄
		button3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				helper.deleteById();
			}
		});
		//批量刪除
		button4.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				helper.deleteByIds();
			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

對應的佈局文件:main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity" >

    <Button 
        android:id="@+id/main_btn_regist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="註冊"/>
    
    <Button 
        android:id="@+id/main_btn_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示"/>
    
    <Button 
        android:id="@+id/main_btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="刪除"/>
    
    <Button 
        android:id="@+id/main_btn_deleteAll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="批量刪除"/>
    
    <TextView 
        android:id="@+id/main_show_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

RegistActivity:用戶註冊類

/**
 * 用戶註冊
 * @author leox
 *
 */
public class RegistActivity  extends Activity {
	EditText userNameEdit;//用戶名編輯框
	EditText passwordEdit;//密碼編輯框
	Button reButton;//註冊按鈕
	
	DatabaseHelper helper = new DatabaseHelper(this);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		userNameEdit = (EditText)this.findViewById(R.id.et_username);
		passwordEdit = (EditText)this.findViewById(R.id.et_password);
		reButton = (Button)this.findViewById(R.id.btn_regist);
		reButton.setOnClickListener(new myClickListener());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	class myClickListener implements OnClickListener{
		@Override
		public void onClick(View v) {
			//用戶名
			String userName = userNameEdit.getText().toString();
			//密碼
			String password = passwordEdit.getText().toString();
			
			User user = new User();
			user.setUserName(userName);
			user.setPassword(password);
			//插入註冊用戶信息
			helper.insert(user);
			Intent intent = new Intent();
			intent.setClass(RegistActivity.this, MainActivity.class);
			startActivity(intent);
		}
		
	}
}

對應的佈局文件:activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".RegistActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="用戶註冊" />
    
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="用戶名:"/>
        <EditText
            android:id="@+id/et_username"
            android:layout_width="200px"
            android:layout_height="wrap_content" />
    </LinearLayout>
    
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密碼:"/>
        <EditText
            android:id="@+id/et_password"
            android:layout_width="200px"
            android:layout_height="wrap_content"
            android:password="true"/>
    </LinearLayout>
    
    <Button 
        android:id="@+id/btn_regist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="註冊"/>

</LinearLayout>








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章