MyBatis入门及CRUD

MyBatis是一个ORM的数据操作框架

myBatis的基本配置

首先创建一个普通 java项目,引入响应jar包,然后引入mybatis的xml配置,

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 3         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 <!--这是一个跟标签-->
 5 <configuration>
 6 
 7     <!--链接properties-->
 8     <properties resource="jdbc.properties" />
 9 
10     <!--设置他的别名 设为包的话别名就是包下面的类名-->
11     <typeAliases>
12   
13         <package name="cn.newsoft.domain"></package>
14     </typeAliases>
15 
16     <!--配置环境们
17     default:默认使用的哪个环境
18     -->
19     <environments default="development">
20         
21         <!--配置单个环境-->
22         <environment id="development">
23             <!--配置事务,有这两个属性
24              JDBC:使用JDBC的默认事务功能
25              MANAGED:表示没有事务
26             -->
27             <transactionManager type="JDBC"/>
28             <!--配置连接池-->
29             <dataSource type="POOLED">
30                 <property name="driver" value="${jdbc.driver}"/>
31                 <property name="url" value="${jdbc.url}"/>
32                 <property name="username" value="${jdbc.username}"/>
33                 <property name="password" value="${jdbc.password}"/>
34             </dataSource>
35         </environment>
36     </environments>
37     <!--引入写sql语句的xml文件-->
38     <mappers>
39         <mapper resource="cn/newsoft/test/productMapper.xml"/>
40     </mappers>
41 </configuration>

配置链接数据库的properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///自己的数据库名
jdbc.username=自己用户名
jdbc.password=数据库密码

然后写好domain对象,然后在测试类写一个xml,这个xml中就是定义自己的sql语句,可以采用别名的方式,解决全限名的问题

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5 
 6 <mapper namespace="cn.newsoft.test.productMapper">
 7     <!--parametertype表示传入参数的类型
 8         resulttype表示每一条数据传出时的类型
 9     -->
          当damian中数据库字段和domain中的不对应时就可以用这个方法来统一字段 10 <resultMap id="prductMap" type="Product"> 11 <result column="dir_id" property="dirId"></result> 12 13 </resultMap> 14 15 <!--查询一个--> 16 <select id="findone" parameterType="long" resultType="Product"> 17 select * from product where id = #{id} 18 </select> 19 20 <!--查询全部--> 21 <select id="findAll" resultMap="prductMap"> 22 select * from product 23 </select> 24 25 <!--添加操作--> 26 <insert id="insert" parameterType="Product"> 27 insert into product(productName,dir_id,salePrice,supplier,brand,cutoff,costPrice) 28 values (#{productName},#{dirId},#{salePrice},#{supplier},#{brand},#{cutoff},#{costPrice}) 29 </insert> 30 31 <!--修改操作--> 32 <update id="update" parameterType="Product" > 33 update product set productName=#{productName},dir_id=#{dirId},salePrice=#{salePrice}, 34 supplier=#{supplier},brand=#{brand},cutoff=#{cutoff},costPrice=#{costPrice} where id=#{id} 35 36 </update> 37 <!--删除一个--> 38 <delete id="delete" parameterType="long"> 39 delete from product where id=#{id} 40 </delete> 41 </mapper>

然后我们定义一个工具类用来获取sqlsession对象

 1 package cn.newsoft.util;
 2 
 3 import org.apache.ibatis.io.Resources;
 4 import org.apache.ibatis.session.SqlSession;
 5 import org.apache.ibatis.session.SqlSessionFactory;
 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 7 
 8 import java.io.IOException;
 9 import java.io.Reader;
10 
11 public class MybatisUtil {
12   private static  SqlSessionFactory build;
13     static {
14         try {
15             Reader resource = Resources.getResourceAsReader("mybatis.xml");
16              build = new SqlSessionFactoryBuilder().build(resource);
17 
18         } catch (IOException e) {
19             e.printStackTrace();
20         }
21     }
22 
23     public static SqlSession gtSession(){
24         SqlSession sqlSession = build.openSession();
25         return sqlSession;
26 
27     }
28 
29 }

dao层为

 1 package cn.newsoft.dao.impl;
 2 
 3 import cn.newsoft.dao.IproductDao;
 4 import cn.newsoft.domain.Product;
 5 import cn.newsoft.util.MybatisUtil;
 6 import org.apache.ibatis.session.SqlSession;
 7 
 8 import java.util.List;
 9 
10 public class ProductImpl implements IproductDao {
11 
12     @Override
13     public void save(Product product) {
14         SqlSession sqlSession = MybatisUtil.gtSession();
15         sqlSession.insert("cn.newsoft.test.productMapper.insert", product);
16 
17     }
18//cn.newsoft.test.productMapper.update"为命名空间的全限定名   update执行的方法名称
19     @Override
20     public void update(Product product) {
21         SqlSession sqlSession = MybatisUtil.gtSession();
22         sqlSession.update("cn.newsoft.test.productMapper.update", product);
23     }
24 
25     @Override
26     public void delete(Long id) {
27         SqlSession sqlSession = MybatisUtil.gtSession();
28         sqlSession.delete("cn.newsoft.test.productMapper.delete", id);
29     }
30 
31     @Override
32     public Product findone(Long id) {
33         SqlSession sqlSession = MybatisUtil.gtSession();
34         Product o = (Product)sqlSession.selectOne("cn.newsoft.test.productMapper.findone",id);
35         return o;
36     }
37 
38     @Override
39     public List<Product> findAll() {
40         SqlSession sqlSession = MybatisUtil.gtSession();
41         List<Product> list = sqlSession.selectList("cn.newsoft.test.productMapper.findAll");
42         return list;
43     }
44 }

然后在测试类中进行测试

 1 package cn.newsoft.test;
 2 
 3 
 4 import cn.newsoft.dao.impl.ProductImpl;
 5 import cn.newsoft.domain.Product;
 6 import cn.newsoft.util.MybatisUtil;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.junit.Test;
 9 
10 import java.util.List;
11 
12 
13 public class IproductDaoTest {
14 
15     ProductImpl products = new ProductImpl();
16     @Test
17     public void save() {
18 
19         Product product = new Product();
20         product.setProductName("sss");
21         product.setSupplier("changcu");
22         products.save(product);
23 
24     }
25 
26     @Test
27     public void update() {
28         Product findone = products.findone(22L);
29         findone.setProductName("李逵");
30         products.update(findone);
31     }
32 
33     @Test
34     public void delete() {
35         products.delete(21L);
36     }
37 
38     @Test
39     public void findone() {
40 
41         Product findone = products.findone(1L);
42         System.out.println(findone);
43     }
44 
45     @Test
46     public void findAll() {
47         List<Product> all = products.findAll();
48     all.forEach(e ->
49             System.out.println(e));
50     }
51 }

这样就完成他的CRUD,

扫描二维码关注公众号,回复: 5766110 查看本文章

日志管理

引入jar包

 1 #log4j.properties(日志文件:)
 2 # ERROR错误的日志 WARN:警告 INFO:普通信息  DEBUG:调试日志  TRACE:日志
 3 log4j.rootLogger=ERROR, stdout
 4 #log4j.rootLogger=NONE
 5 #把左边包名改成你自己的包名
 6 log4j.logger.cn.itsource=TRACE
 7 
 8 # 日志打印到控制台中
 9 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
10 # 日志打印的一种格式(可以灵活地指定布局模式)
11 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
12 # 日志打印的格式是什么样子的  %d:日期 %p:优先级 %c:类的全名  %m:输出的结果 %n:换行
13 log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

猜你喜欢

转载自www.cnblogs.com/xiaohuziguai/p/10651104.html