转自:http://blog.csdn.net/lenotang/article/details/2809578
1.做一个DTO类Student
package com.wepull.student.model;
public class Student {
private int id;
private String name;
private int age;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2.做一个查询条件类Cond
package com.wepull.student.model;
/**
* @author leno
* javabean风格的简单查询条件类
*/
public class Cond {
private String colName;
private String operation;
private String colValue;
public String getColName() {
return colName;
}
public void setColName(String colName) {
this.colName = colName;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getColValue() {
return colValue;
}
public void setColValue(String colValue) {
this.colValue = colValue;
}
}
3.做一个操作学生对象的DAO的接口
package com.wepull.student.model;
import java.util.List;
public interface IStudentDAO {
public void insert(Student stu);
public void edit(Student stu);
public void del(int id);
public Student findById(int id);
public int getRecords();
public List<Student> findAll();
public List<Student> findAll(int page,int pageSize);
public List<Student> findAll(List<Cond> cond,int page,int pageSize);
}
4. 做一个操作学生对象的DAO的实现类,该类就是重点
package com.wepull.student.model;
public class StudentDaoImpl implements IStudentDao
{
private String xmlPath = "student.xml";
private Document doc;
{
init();
}
/**
* 初始化工作,xml文件存在而读取
* 不存在则按照一定格式在当前工程下创建
*/
public void init()
{
File file = new File(xmlPath);
if (file.exists())
{
SAXReader reader = new SAXReader();
try
{
doc = reader.read(file);
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
doc = DocumentHelper.createDocument();
//使用addDocType()方法添加文档型说明
doc.addDocType("student", null, "student.dtd");
Element root = doc.addElement("students");
root.addComment("student's information");
overRideXml();
}
}
public StudentDaoImpl()
{
// TODO Auto-generated constructor stub
}
public StudentDaoImpl(String xmlPath)
{
}
public void delete(int id)
{
// TODO Auto-generated method stub
Element element = findElementById(id);
if (null != element)
{
doc.getRootElement().remove(element);
overRideXml();
}
}
public void edit(Student stu)
{
// TODO Auto-generated method stub
int id = stu.getId();
Element element = findElementById(id);
if (null != element)
{
element.element("name").setText(stu.getName());
element.element("age").setText(String.valueOf(stu.getAge()));
overRideXml();
}
}
@SuppressWarnings("unchecked")
public List<Student> findAll()
{
// TODO Auto-generated method stub
List<Student> list = new ArrayList<Student>();
Element root = doc.getRootElement();
Iterator it = root.elementIterator();
while (it.hasNext())
{
//TODO attributeValue和elementText区别
Element element = (Element)it.next();
Student stu = new Student();
stu.setId(Integer.parseInt(element.attributeValue("id")));
stu.setName(element.elementText("name"));
stu.setAge(Integer.parseInt(element.elementText("age")));
list.add(stu);
}
return list;
}
@SuppressWarnings("unchecked")
public List<Student> findAll(int page, int pageSize)
{
// TODO Auto-generated method stub
List<Student> list = new ArrayList<Student>();
Element root = doc.getRootElement();
List<Element> allList = root.elements();
int size = allList.size();
int maxPage = (size + pageSize - 1) / pageSize;
if (0 == size || page < 1 || page > maxPage)
{
return list;
}
int start = (page - 1) * pageSize;
int end = start + pageSize;
if(end > size)
{
end = allList.size();
}
List<Element> eleList = allList.subList(start, end);
Iterator<Element> it = eleList.iterator();
while(it.hasNext())
{
Element element = it.next();
Student stu = new Student();
stu.setId(Integer.parseInt(element.attributeValue("id")));
stu.setName(element.elementText("name"));
stu.setAge(Integer.parseInt(element.elementText("age")));
list.add(stu);
}
return list;
}
/**
* 分页并且按照条件查询学生数据(有待加强和优化)
*/
@SuppressWarnings("unchecked")
public List<Student> findAll(List<Cond> conds, int page, int pageSize) {
List<Student> list = new ArrayList<Student>();
Element root = doc.getRootElement();
List<Element> allList = new ArrayList<Element>();
Iterator<Element> allIt = root.elementIterator();
while (allIt.hasNext()) {
Element element = allIt.next();
String id = element.attributeValue("id");
String name = element.elementText("name");
String age = element.elementText("age");
for (int i = 0; i < conds.size(); i++) {
Cond cond = conds.get(i);
String colName = cond.getColName();
String operation = cond.getOperation();
String colValue = cond.getColValue();
if ("id".equals(colName)) {
if (operation.equals("=")) {
if (!id.equals(colValue)) {
break;
}
}
} else if ("name".equals(colName)) {
if (operation.equals("=")) {
if (!name.equals(colValue)) {
break;
}
} else if (operation.equals("like")) {
if (!name.contains(colValue)) {
break;
}
}
} else if ("age".equals(colName)) {
if (operation.equals("=")) {
if (!age.equals(colValue)) {
break;
}
}
}
}
allList.add(element);
}
int size = allList.size();
int maxPage = (size + pageSize - 1) / pageSize;
if (size == 0 || page < 1 || page > maxPage) {
return list;
}
int start = (page - 1) * pageSize;
int end = start + pageSize;
if (end > size) {
end = allList.size();
}
List<Element> eleList = allList.subList(start, end);
Iterator<Element> it = eleList.iterator();
while (it.hasNext()) {
Element element = it.next();
Student stu = new Student();
stu.setId(Integer.parseInt(element.attributeValue("id")));
stu.setName(element.elementText("name"));
stu.setAge(Integer.parseInt(element.elementText("age")));
list.add(stu);
}
return list;
}
public Student findById(int id)
{
// TODO Auto-generated method stub
Student stu = null;
Element element = findElementById(id);
if(element != null)
{
stu = new Student();
stu.setId(id);
stu.setName(element.elementText("name"));
stu.setAge(Integer.parseInt(element.elementText("age")));
}
return stu;
}
public int getRecords()
{
// TODO Auto-generated method stub
return doc.getRootElement().elements().size();
}
public void insert(Student stu)
{
// TODO Auto-generated method stub
int currId = getMaxId() + 1;
Element root = doc.getRootElement();
Element student = root.addElement("student");
student.addAttribute("id", String.valueOf(currId));
Element name = student.addElement("name");
name.setText(stu.getName());
Element age = student.addElement("age");
age.setText(String.valueOf(stu.getAge()));
overRideXml();
}
@SuppressWarnings("unchecked")
public Element findElementById(int id)
{
Iterator<Element> it = doc.getRootElement().elementIterator("student");
while(it.hasNext())
{
Element element = it.next();
if(String.valueOf(id).equals(element.attributeValue("id")))
{
return element;
}
}
return null;
}
@SuppressWarnings({"unchecked", "unchecked"})
private int getMaxId()
{
int maxId = 0;
Element root = doc.getRootElement();
Iterator<Element> it = root.elementIterator("student");
while(it.hasNext())
{
Element element = (Element) it.next();
String id = element.attributeValue("id");
if(maxId < Integer.parseInt(id))
{
maxId = Integer.parseInt(id);
}
}
System.out.println("maxId" + maxId);
return maxId;
}
private void overRideXml()
{
XMLWriter writer = null;
try
{
writer = new XMLWriter(new FileOutputStream(xmlPath),OutputFormat.createPrettyPrint());
writer.write(doc);
writer.close();
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
IStudentDAO dao = new StudentDAO();
// System.out.println(dao.getRecords());
// for (int i = 0; i < 40; i++) {
// Student stu = new Student();
// //stu.setId(2);
// stu.setName("www");
// stu.setAge(233);
// dao.insert(stu);
// }
List<Cond> conds = new ArrayList<Cond>();
for (int i = 0; i < 1; i++) {
Cond cond = new Cond();
cond.setColName("name");
cond.setOperation("like");
cond.setColValue("1");
conds.add(cond);
}
List<Student> list = dao.findAll(conds, 1, 20);
Iterator<Student> it = list.iterator();
while (it.hasNext()) {
Student stu = it.next();
System.out.println(stu.getId() + " " + stu.getName());
}
}
}
5. 将如下student.dtd文件放在当前工程目录下
<!ELEMENT students (student*)>
<!ELEMENT student (name,age)>
<!ATTLIST student id CDATA #IMPLIED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>