(5)MyBatis小总结:一个简单的例子

网友投稿 622 2022-10-16

(5)MyBatis小总结:一个简单的例子

(5)MyBatis小总结:一个简单的例子

日期:2017/12/6

求职中,加紧学习。(引用自某位前辈)

mybatis即是对JDBC的封装(重复代码的优秀封装),因为是半自动化ORM,所以sql其实需要我们自己写和封装的(xml标签装饰),下面介绍一个最简单的使用例子,实现“select * from employee where id=1”。

准备:

1. Mysql ,eclipse ;

2. jar包: mybatis-3.4.1.jar 、mysql-connector-java-5.1.37-bin.jar、log4j.jar(​​java常用开发包--log4j.jar ​​)

3. 目录结构:

|configuration.xml

|testcase.java

|User.java

|User.xml

4.代码

4.1User.java:

package mybatis;public class User { private Integer id; private String lastName; private String email; private String gender; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + "]"; } }

4.2 configuration.xml:

User.xml:

4.4 testcase.java:

package mybatis;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 testcase { public static void main(String[] args) throws IOException { String resource = "mybatis/configuration.xml"; Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader); SqlSession session = ssf.openSession(); try { User user = (User) session.selectOne("User.selectUser", "1"); System.out.println(user); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } }}

测试结果:

log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).log4j:WARN Please initialize the log4j system properly.

Employee [id=1, lastName=mmb, email=144@qq.com, gender=0]

测试可用。WHAT IS MORE :​​(6)MyBatis小总结:一个简单的例子--接口编程改进​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:AndroMDA- MDA建模框架
下一篇:技术分享|如何实现小程序与App的跳转,微信小程序跳转APP怎么设置
相关文章

 发表评论

暂时没有评论,来抢沙发吧~