【Saas-export專案】--專案整合(實體類、整合mybatis、service)

sumengpan發表於2020-10-24



匯入資料庫

  • 呼叫圖形化工具執行sql檔案
    在這裡插入圖片描述

  • 資料庫表如下:

在這裡插入圖片描述

建立專案

https://blog.csdn.net/qq_41209886/article/details/109216349

  • 父工程export-parent
  • 子工程export-dao
    export-domain
    export-service
    export-webmanager

準備實體類domain

在這裡插入圖片描述

import java.util.Date;

//企業實體類
public class Company {

    public Company() {
    }

    @Override
    public String toString() {
        return "Company{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", expirationDate=" + expirationDate +
                ", address='" + address + '\'' +
                ", licenseId='" + licenseId + '\'' +
                ", representative='" + representative + '\'' +
                ", phone='" + phone + '\'' +
                ", companySize='" + companySize + '\'' +
                ", industry='" + industry + '\'' +
                ", remarks='" + remarks + '\'' +
                ", state=" + state +
                ", balance=" + balance +
                ", city='" + city + '\'' +
                '}';
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getExpirationDate() {
        return expirationDate;
    }

    public void setExpirationDate(Date expirationDate) {
        this.expirationDate = expirationDate;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getLicenseId() {
        return licenseId;
    }

    public void setLicenseId(String licenseId) {
        this.licenseId = licenseId;
    }

    public String getRepresentative() {
        return representative;
    }

    public void setRepresentative(String representative) {
        this.representative = representative;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getCompanySize() {
        return companySize;
    }

    public void setCompanySize(String companySize) {
        this.companySize = companySize;
    }

    public String getIndustry() {
        return industry;
    }

    public void setIndustry(String industry) {
        this.industry = industry;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    /**
     * 物件唯一標記,對應資料庫主鍵
     */
    private String id;
    /**
     * 公司名稱
     */
    private String name;

    /**
     * 到期時間
     */
    private Date expirationDate;

    /**
     * 公司地址
     */
    private String address;
    /**
     * 營業執照
     */
    private String licenseId;
    /**
     * 法人代表
     */
    private String representative;
    /**
     * 公司電話
     */
    private String phone;
    /**
     * 公司規模
     */
    private String companySize;
    /**
     * 所屬行業
     */
    private String industry;
    /**
     * 備註
     */
    private String remarks;

    /**
     * 狀態
     */
    private Integer state;
    /**
     * 當前餘額
     */
    private Double balance;

    /**
     * 城市
     */
    private String city;

}

dao層Spring整合MyBatis進行資料庫訪問(export_dao子工程)

在這裡插入圖片描述

檢查 pom.xml

有沒有spring與mybatis的整合包

export_dao\pom.xml

    <!-- 子工程繼承父工程,可以使用父工程中的配置-->
    <!-- A子工程 依賴 B子工程,可以使用裡面的B子工程 java類-->
    <dependencies>
        <dependency>
            <artifactId>export_domain</artifactId>
            <groupId>com.smp</groupId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

(1)properties/db.properties

#key=value
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/saas-export?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

(2)spring/applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--讀取db.properties檔案-->
    <context:property-placeholder location="classpath:properties/db.properties"></context:property-placeholder>

    <!--1.配置資料來源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--2.配置Spring整合Mybatis *** 由Spring建立SqlSessionFactory物件-->
    <!--2.1 配置SqlSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入資料來源-->
        <property name="dataSource" ref="dataSource"/>
        <!-- com.smp.domain.company.Company  company-->
        <property name="typeAliasesPackage" value="com.smp.domain"/>
    </bean>

    <!--2.2 配置Dao介面所在包 動態代理 session.getMapper(Dao.class)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定Dao介面所在包-->
        <property name="basePackage" value="com.smp.dao"/>
    </bean>

</beans>

(3)定義ICompanyDao

import com.smp.domain.company.Company;

import java.util.List;

public interface ICompanyDao {
    //查詢所有的公司紀錄
    //select * from ss_company;
    List<Company> findAll();
}

(4)定義ICompanyDao.xml

<?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="com.smp.dao.company.ICompanyDao">

    <!--<select id="findAll" resultType="company">
select
	id,
	name ,
	expiration_date as expirationDate ,
	address,
	license_id as licenseId  ,
	representative ,
	phone  ,
	company_size as companySize  ,
	industry  ,
	remarks ,
	state,
	balance ,
	city
from ss_company
    </select>-->

    <!--//查詢所有的公司紀錄
    //select * from ss_company;
    List<Company> findAll();-->
    <resultMap id="companyMap" type="company">
        <id column="id" property="id"/>
        <result column="expiration_date" property="expirationDate"/>
        <result column="license_id" property="licenseId"/>
        <result column="company_size" property="companySize"/>
    </resultMap>
    <select id="findAll" resultMap="companyMap">
        select * from ss_company
    </select>
</mapper>

(5)測試

src\test\java\com\smp\dao\company\ICompanyDaoTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-dao.xml")
public class ICompanyDaoTest {
    @Autowired
    ICompanyDao iCompanyDao;
    @Test
    public void findAll(){
        System.out.println(iCompanyDao);
        List<Company> list=iCompanyDao.findAll();
        System.out.println(list);
    }
}

測試結果

在這裡插入圖片描述

service依賴dao

測試讀取dao的資訊,配置事務管理(export_system_service子工程)
子工程export_system_service依賴子工程export_domain
在這裡插入圖片描述

關於classpath路徑讀取的使用

@ContextConfiguration("classpath*:spring/applicationContext-*.xml")

classpath: 載入當前maven工程的resources目錄下的配置檔案
classpath*: 載入當前maven工程及其依賴工程的resources目錄下的配置檔案
applicationContext-*.xml: 讀取所有符合規則的檔案

(1)TestCompanyService.java測試

src\test\java\com\smp\service\company

//新增spring單元測試
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-*.xml")
public class TestCompanyService {
    @Autowired
    ICompanyService service;
    @Test
    public void test01(){
        //編寫業務邏輯測試
        //左邊介面,右邊實現類
        //ICompanyService service= new CompanyServiceImpl();
        List<Company> list=service.findAll();
        System.out.println(list);
    }
}

(2)applicationContext-tx.xml事務管理

src\main\resources\spring

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--掃描Service實現類-->
    <context:component-scan base-package="com.smp.service"/>


    <!--Spring宣告式事務(底層就是AOP): 三步曲-->

    <!--1.配置事務管理器:管理事務:DataSource.Connection.commit() rollback()方法  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入資料來源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--2.配置事務通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager" >
        <!--配置事務細節特徵-->
        <tx:attributes>
            <!--查詢方法,使用預設的隔離級別 及 SUPPORTS傳播行為-->
            <tx:method name="find*" isolation="DEFAULT" propagation="SUPPORTS"/>
            <tx:method name="query*" isolation="DEFAULT" propagation="SUPPORTS"/>
            <tx:method name="select*" isolation="DEFAULT" propagation="SUPPORTS"/>
            <tx:method name="get*" isolation="DEFAULT" propagation="SUPPORTS"/>
            <!--增刪改方法,使用預設的隔離級別 及 REQUIRED傳播行為-->
            <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--3.配置事務切面: 切面=通知+切入點-->
    <aop:config>
        <!--配置切入點-->
        <aop:pointcut id="pt" expression="execution(* com.smp.service.*.impl.*.*(..))"/>

        <!--切面=通知+切入點-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    </aop:config>

</beans>

(3)ICompanyService.java介面

src\main\java\com\smp\service\company

public interface ICompanyService {

    List<Company> findAll();
}

(4)CompanyServiceImpl.java實現類

src\main\java\com\smp\service\company\impl

@Service
public class CompanyServiceImpl implements ICompanyService {
    @Autowired
    ICompanyDao iCompanyDao;
    public List<Company> findAll() {
        return iCompanyDao.findAll();
    }
}

(5)配置spring事務時遇到了dataSource錯誤

applicationContext.xml無法解析資料來源dataSource
在這裡插入圖片描述
產生的原因是spring的配置檔案沒有匯入,需要手動匯入

  • 點選File——》Project structure——》

在這裡插入圖片描述

  • Moudles–>點選+號–>勾選上配置檔案–>ok–>apply–>ok即可
    在這裡插入圖片描述

相關文章