MyBatis CRUD Java POJO操作
<?xml version="1.0" encoding="UTF-8" ?> <!-- Copyright 2009-2012 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- <settings> <setting name="useGeneratedKeys" value="false"/> <setting name="useColumnLabel" value="true"/> </settings> <typeAliases> <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/> </typeAliases> --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="" value="" /> </transactionManager> <dataSource type="UNPOOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" /> <property name="username" value="root" /> <property name="password" value="mysql" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/stone/config/sqlxml/Person.xml" /> <mapper class="com.stone.dao.IPersonMapper"/> </mappers> </configuration>
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2009-2012 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="Person"> <resultMap type="com.stone.bean.Person" id="PersonResult"> <!-- jdbcType就是java.sql.Types.后面的名称 --> <id column="ID" jdbcType="INTEGER" property="id" /> <result column="NAME" jdbcType="VARCHAR" property="name" /> <result column="BIRTHDAY" jdbcType="TIMESTAMP" property="birthday" /> </resultMap> <select id="queryPersonList" resultMap="PersonResult"> SELECT ID,NAME,BIRTHDAY FROM person </select> <select id="queryPerson2" resultType="com.stone.bean.Person"> SELECT ID,NAME,BIRTHDAY FROM person </select> <insert id="insertPerson" parameterType="com.stone.bean.Person"> insert into person(name,birthday) values(#{name},#{birthday}); </insert> <delete id="delPerson" parameterType="int"> delete from person where id=#{id} </delete> <select id="selPerson" parameterType="int" resultType="com.stone.bean.Person"> select id,name,birthday from person where id=#{id} </select> <update id="updatePerson" parameterType="com.stone.bean.Person"> update person set name=#{name},birthday = #{birthday} where id=#{id} </update> <select id="version" parameterType="long" resultType="int"> SELECT version FROM user WHERE id = #{id,jdbcType=INTEGER} </select> </mapper>
package com.stone.db; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; /** * 访问数据库类 */ public class DBAccess { public SqlSession getSqlSession() throws IOException { // 通过数据库文件获取数据库连接 Reader reader = Resources .getResourceAsReader("com/stone/config/Configuration.xml"); // 通过配置信息构建一个SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(reader); // 获取SqlSessionFactory的第二种方法; // InputStream inputStream = DBAccess.class // .getResourceAsStream("com/stone/config/Configuration.xml"); // SqlSessionFactory factory = new SqlSessionFactoryBuilder() // .build(inputStream); // 通过SqlSessoinFactory打开一个数据库会话 SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession; } }
package com.stone.bean; import java.text.SimpleDateFormat; import java.util.Date; public class Person { private int id; private String name; private Date birthday; 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 Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:SS"); return "Person [id=" + id + ", name=" + name + ", birthday=" + dateFormat.format(birthday) + "]"; } }
package com.stone.dao; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.stone.bean.Person; import com.stone.db.DBAccess; public class DBDao { public List<Person> queryPerson() { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; List<Person> persons = new ArrayList<Person>(); try { sqlSession = dbAccess.getSqlSession(); // 通过sqlSession执行SQL语句; persons = sqlSession.selectList("Person.queryPersonList"); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } return persons; } public List<Person> queryPerson2() { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; List<Person> persons = new ArrayList<Person>(); try { sqlSession = dbAccess.getSqlSession(); // 通过sqlSession执行SQL语句; persons = sqlSession.selectList("Person.queryPerson2"); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } return persons; } public void insertPerson(Person person) { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; try { sqlSession = dbAccess.getSqlSession(); String statement = "Person.insertPerson"; // int The number of rows affected by the insert. int insert = sqlSession.insert(statement, person); System.out.println("insert result:" + insert); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } public void deletePerson(int id) { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; try { sqlSession = dbAccess.getSqlSession(); String statement = "Person.delPerson"; int delete = sqlSession.delete(statement, id); System.out.println("delete rownums:" + delete); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } public Person getPerson(int id) { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; Person person = null; try { sqlSession = dbAccess.getSqlSession(); String statement = "Person.selPerson"; person = sqlSession.selectOne(statement, id); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } return person; } public int insertPerson2() { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; int insertPerson = -1; try { sqlSession = dbAccess.getSqlSession(); IPersonMapper mapper = sqlSession.getMapper(IPersonMapper.class); Person person = new Person(); person.setName("name2"); person.setBirthday(new Date()); insertPerson = mapper.insertPerson(person); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } return insertPerson; } public static void main(String[] args) { DBDao dbDao = getPersons(); System.out.println("================="); List<Person> persons2 = getPersons2(dbDao); System.out.println("================="); insertPerson(dbDao); System.out.println("================="); dbDao.deletePerson(persons2.get(0).getId()); System.out.println("================="); System.out.println(dbDao.getPerson(persons2.get(1).getId())); System.out.println("================="); System.out.println(dbDao.insertPerson2()); } private static void insertPerson(DBDao dbDao) { Person person = new Person(); person.setName("name"); person.setBirthday(new Date()); dbDao.insertPerson(person); } private static List<Person> getPersons2(DBDao dbDao) { List<Person> list2 = dbDao.queryPerson2(); for (Person person : list2) { System.out.println(person); } return list2; } private static DBDao getPersons() { DBDao dbDao = new DBDao(); List<Person> list = dbDao.queryPerson(); System.out.println(list.size()); for (Person person : list) { System.out.println(person); } return dbDao; } }
package com.stone.dao; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.stone.bean.Person; public interface IPersonMapper { @Insert("insert into person(name,birthday) values(#{name},#{birthday})") public int insertPerson(Person person); @Delete("delete from person where id=#{id}") public int deletePersonById(Person person); @Update("update person set name=#{name},birthday=#{birthday} where id=#{id}") public int updatePerson(Person person); @Select("select id,name,birthday from person where id=#{id}") public Person getPersonById(int id); @Select("select id,name,birthday from person") public List<Person> getPerons(); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。