Project Record 1 (eclipse to idea, Hibernate to Mybatis)

Project scenario:

I used eclipse before to make a soil proportioner project, using the old SSH architecture. Now that I have used IDEA and learned some mybatis, I will try this.

Go through the process:

1. From eclipse to idea

(1) Create a new maven project in the idea --> Question: How to add web functions to the newly created maven project
(2) Change <packaging>jar</packaging> in pom.xml to war, and create a new web directory in the project directoryinsert image description here

(3) Click in the upper right corner of the newly created maven project insert image description here
to change this to classes in the web directory, and the classes turn yellow insert image description here
(4) Add Tomcat in the upper right corner, and add your project at the position shown in the figure below
insert image description here
(5) After that, copy the code of the corresponding directory in eclipse to the idea.

Summary:
1. The environment of the new maven project should be the same as that in eclipse (jdk, maven, Tomcat).
2. When there is a jar package in the lib, select Jars or directories in Project Structure->Modules->Dependies to add the lib package.
3. Pay attention to modify the jar in pom.xml to war, otherwise the project cannot be found in Tomcat.
Development:
1. Try to import the eclipse project directly into idea.


Two, hibernate to mybatis

(1) Delete the hibernate references in xxxx.hbm.xml, hibernate.cfg.xml and pom.xml in the original project.

(2) Add mybatis reference in pom.xml

		<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
		</dependency>

(3) Create files at the same level in the Java and resources directories (with the same name)
insert image description here

(4) Create configuration files and write configuration files
insert image description here

(5) Write the corresponding interface and xml file
Interface file IShopBeanDao:

public interface IShopBeanDao {
    
    
	 boolean deleteShopBean(int id);
	 List<ShopBean> getAllList();
	 ShopBean getShopById (int id);
}

IShopBeanDao.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.demo.dao.IShopBeanDao">

    <!-- 配置 查询结果的列名和实体类的属性名的对应关系 -->
    <resultMap id="ShopBeanMap" type="ShopBean">
        <!-- 主键字段的对应 -->
        <id property="id" column="id"></id>
        <!--非主键字段的对应-->
        <result property="companyName" column="companyName"></result>
        ...等等...
    </resultMap>

    <!-- 查询所有 -->
    <select id="getAllList" resultMap="ShopBeanMap">
        select * from shopbean order by id;
    </select>
    <!-- 删除-->
    <delete id="deleteShopBean" parameterType="java.lang.Integer">
        delete from shopbean where id = #{id}
    </delete>
    <!-- 根据id查询用户 -->
    <select id="getShopById" parameterType="INT" resultMap="ShopBeanMap">
        select * from shopbean where id = #{id}
    </select>
</mapper>

(6) Create a simple test class in test->java to test whether the data can be read

public class MybatisTest {
    
    

    private InputStream in;
    private SqlSession sqlSession;
    private IShopBeanDao shopBean;

    @Before//用于在测试方法执行之前执行
    public void init()throws Exception{
    
    
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession();
        //4.获取dao的代理对象
        shopBean =  sqlSession.getMapper(IShopBeanDao.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy()throws Exception{
    
    
        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }

    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll(){
    
    
        //5.执行查询所有方法
        List<ShopBean> shopBeans = shopBean.getAllList();
        for(ShopBean s : shopBeans){
    
    
            System.out.println(s);
        }
        new SessionFactory().destroyFactory(sqlSession);

    }
 }

(7) Complete the remaining interfaces and xml files.
1. Solve the self-growth and return display of the id primary key during the saving process

<!-- 保存 -->
    <insert id="insert" parameterType="pbBean">
        <!-- 配置插入操作后,获取插入数据的id -->
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into pbBean(conpanyid,conpanyname,peibi,summoney)values(#{conpanyid},#{conpanyname},#{peibi},#{summoney});
    </insert>

2. Solve the saving and query of multiple objects in an xml file
and create multiple <resultMap></resultMap>

    <!-- 配置 pbBean -->
    <resultMap id="pbBeanMap" type="pbBean">
        <!-- 主键字段的对应 -->
        <id property="id" column="id"></id>
        <!--非主键字段的对应-->
        <result property="conpanyid" column="conpanyid"></result>
        ***等等***
    </resultMap>

    <!-- 配置 PeiBiMuLu -->
    <resultMap id="PeiBiMuLuMap" type="PeiBiMuLu">
        <!-- 主键字段的对应 -->
        <id property="id" column="id"></id>
        <!--非主键字段的对应-->
        <result property="PeiBiMingZi" column="peiBiMingZi"></result>
        ***等等***
    </resultMap>

3. Solve the use of multi-condition query function (one object, one String) in mybatis
to modify the method in the interface file

List<PeibiBiao> getPeiBiBiao(@Param("testbean")testbean testBean,@Param("biaoDan_id")String biaoDan_id);

Modify the query method in the xml file

<!-- 查询所有 -->
    <select id="getPeiBiBiao" resultMap="PeibiBiaoMap">
        select * from PeibiBiao where na = #{testbean.na} and fenShuId = #{biaoDan_id} order by summoney;
    </select>

(8) Create a SessionFactory factory and modify the corresponding Java file
SessionFactory.java

public class SessionFactory {
    
    
    public SqlSession initFactory(){
    
    
        InputStream in;
        try {
    
    
            //1.读取配置文件,生成字节输入流
            in = Resources.getResourceAsStream("SqlMapConfig.xml");
            //2.获取SqlSessionFactory
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
            in.close();
            //3.获取SqlSession对象
            return factory.openSession();
        } catch (Exception e){
    
    
            System.out.println("session获取失败");
        }
        return null;
    }
    public void destroyFactory(SqlSession sqlSession){
    
    
        System.out.println("关闭");
        //4.提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
    }
}

In other Java files use:

public class ShopAction {
    
    
    private SqlSession sqlSession;
	private IShopBeanDao IshopBean;
	public List<ShopBean> findAll(){
    
    
//	    1.获取session
		sqlSession = new SessionFactory().initFactory();
//		2.代理对象
		IshopBean = sqlSession.getMapper(IShopBeanDao.class);
//		3.业务逻辑
        List<ShopBean> shopBeans = IshopBean.getAllList();
//      4.结束session
        new SessionFactory().destroyFactory(sqlSession);
		return shopBeans;
	}
}

Summary:
1. When creating an xml directory in resources, it is built layer by layer (❌cn.demo.dao is wrong). It is best not to choose to fold the directory, and uncheck it as shown in the figure. The variable in the input method, if it is an object, fill in the
insert image description here
Type of
resultMap . 4. When writing the xml method, use the <, > and other symbols in the sql statement to refer to the figure below


insert image description here

5. When writing the save method in xml, when the id of the object is the primary key, try not to write id in sql.
6. When modifying other Java files, pay attention to the closing time of sqlSession

Development:
1. Use annotations to implement
2. When modifying the sequence, first write the tool class -> write a simple test class -> modify the rest of the Java files -> write the xml file corresponding to the interface.
3. Pay attention to naming conventions when writing objects


Project link:

https://blog.csdn.net/qq_38922932/article/details/108608045

Guess you like

Origin blog.csdn.net/qq_38922932/article/details/108540150