每日记录(十一)2023.03.03

今天,学习了mybatis的基本东西

esource/mybatis-config.xml

写SQL语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
        <package name="com.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;allowPublicKeyRetrieval=true&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="wmx021207"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--扫描mapper-->
       
<package name="com.mapper"/>
    </mappers>
</configuration>

MybatisDemo

String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);





//2、获取sql.....对象,用来执行sql
       
SqlSession sqlSession = sqlSessionFactory.openSession();


//执行sql语句
       
List<User> users = sqlSession.selectList("test.selectAll");

        System.out.println(users);
#
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = mapper.selectAll();

for(Brand u:brands)
{
    System.out.println(u);
}
 
#

//4、释放资源

       
sqlSession.close();

……Mapper.xml

pper namespace="com.mapper.BrandMapper">

<!--数据库表的字段名称和实体类的不一样,则不能自动封装数据
*
起别名:对不一样的列名起别名,让别名和实体类的属性名一样
*
缺点:每次查询都要定义一次别名
*resultMap
-->

   
<resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
    </resultMap>


    <select id="selectAll" resultMap="brandResultMap">
        select * from tb_brand;
    </select>
posted @ 2023-03-03 21:43  傲世小苦瓜  阅读(11)  评论(0)    收藏  举报