一屎蜓、使用 PowerDesigner 工具
-
1. 新建模型 PDM(物理數(shù)據(jù)模型)
- 將該模型的數(shù)據(jù)庫設置為 MySQL
- 新增三張表然评,Student(學生)颖榜, Subject(課程), Score(成績)
- 其中 Student 和 Subject 是主表
- Score 分別是 Student 和 Subject 的從表教沾,某個成績一定是某個學生某門課程的成績
- 設置外鍵時蒲跨,直接使用 referecnes 拉線就可以完成,從從表拉向主表
- 設置自增時授翻,將 identity 勾選
- 選擇生成數(shù)據(jù)庫腳本 DDL 以及測試數(shù)據(jù)腳本 DML 或悲,在對應的 MySQL 數(shù)據(jù)庫中執(zhí)行孙咪,生成數(shù)據(jù)庫以及測試數(shù)據(jù)
- 這樣就生成帶有各種外鍵約束的,非空的巡语,唯一的翎蹈,自增的,主鍵的表的結(jié)構(gòu)
-
2. 將生成好的 PDM 轉(zhuǎn)換為 CDM(概念數(shù)據(jù)模型)
- 之前的三張表 table 變成三個 Entity 實體
- 而且實體之間也有正確的對應關(guān)系男公,一對一荤堪,一對多,多對一枢赔,多對多
-
3. 還可以將 PDM 生成 OOM(面向?qū)ο竽P停?/strong>
- 之前的三張表變成了三個 class 文件
- 而且類與類之間的關(guān)系也自動生成好了
- 對一用對象澄阳,對多用數(shù)組
- 該類要進行使用時,可能要根據(jù)業(yè)務做具體的調(diào)整
-
4. 還可以將 PDM 轉(zhuǎn)換為 xml 的約束
- 之前的三個表變成了三個 xsd 文件
- 在各自的 xsd 文件中指定了 xml 文件的約束
二踏拜、操作mysql
- 將第一步生成好的 DDL 在 MySQL 中執(zhí)行生成對應的數(shù)據(jù)庫
- 將測試數(shù)據(jù)的 DML 腳本在數(shù)據(jù)庫中執(zhí)行碎赢,生成對應的測試數(shù)據(jù)
- 注意一些運維的細節(jié)
- 注意 MySQL 數(shù)據(jù)庫以及每張數(shù)據(jù)表的編碼格式
- sql 文件
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for score -- ---------------------------- DROP TABLE IF EXISTS `score`; CREATE TABLE `score` ( `scid` int(11) NOT NULL AUTO_INCREMENT, `sid` int(11) NULL DEFAULT NULL, `suid` int(11) NULL DEFAULT NULL, `score` decimal(10, 2) NOT NULL, `sdesc` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`scid`) USING BTREE, INDEX `FK_sc_c`(`sid`) USING BTREE, INDEX `FK_sc_su`(`suid`) USING BTREE, CONSTRAINT `FK_sc_c` FOREIGN KEY (`sid`) REFERENCES `student` (`sid`) ON DELETE RESTRICT ON UPDATE RESTRICT, CONSTRAINT `FK_sc_su` FOREIGN KEY (`suid`) REFERENCES `subject` (`suid`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of score -- ---------------------------- INSERT INTO `score` VALUES (1, 1, 1, 100.00, 'AA'); INSERT INTO `score` VALUES (2, 2, 2, 90.00, 'BB'); INSERT INTO `score` VALUES (3, 3, 3, 100.00, 'CC'); -- ---------------------------- -- Table structure for student -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `sid` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `pass` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `tel` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `addr` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `age` int(11) NOT NULL, PRIMARY KEY (`sid`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 21 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of student -- ---------------------------- INSERT INTO `student` VALUES (1, 'AAA', '111111', '11111111111', 'AA', 17); INSERT INTO `student` VALUES (2, 'BBB', '111111', '11111111111', 'BB', 13); INSERT INTO `student` VALUES (3, 'CCC', '222222', '11111111111', 'CC', 11); -- ---------------------------- -- Table structure for subject -- ---------------------------- DROP TABLE IF EXISTS `subject`; CREATE TABLE `subject` ( `suid` int(11) NOT NULL AUTO_INCREMENT, `suname` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `degree` int(11) NOT NULL, PRIMARY KEY (`suid`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of subject -- ---------------------------- INSERT INTO `subject` VALUES (1, 'AAA', 90); INSERT INTO `subject` VALUES (2, 'BBB', 90); INSERT INTO `subject` VALUES (3, 'CCC', 80); SET FOREIGN_KEY_CHECKS = 1;
三、使用 EasyCode 插件將 MySQL 中的數(shù)據(jù)表使用逆向工程來生成對應 pojo速梗,dao肮塞,xml 方式,甚至是 service 以及 controller
- 首先在 IDEA 中打開 database 界面
- 分別設置數(shù)據(jù)庫姻锁、用戶名和密碼新增一個 MySQL 的鏈接
- 打開數(shù)據(jù)庫中的schemaS枕赵,選擇你要逆向生成的表(可以多選)
- 右鍵 EasyCode --> 點擊 Generate Code
- 選擇自己的 package(可以提前建好),選擇所有 ' all '位隶,可以去掉 debug.json 拷窜,選擇禁止提示來防止多次提示是否生成子目錄
- 正常情況會在剛剛選擇的包下分別生成 controller,entity涧黄,service 以及 dao 子包以及接口装黑、實現(xiàn)類、xml
- 正常情況弓熏,EasyCode會在 resources 下生成 mapper 文件夾以及 dao 的 .xml 文件,注意手動將其配置在與 dao 接口平級的 resources 目錄下
- 基本骨架生成成功
四糠睡、搭建 SSM
- 添加依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com</groupId> <artifactId>SSM-EasyCode</artifactId> <version>1.0-SNAPSHOT</version> <!-- web項目 --> <packaging>war</packaging> <properties> <!-- 統(tǒng)一管理spring相關(guān)產(chǎn)品的版本 --> <spring-version>4.3.9.RELEASE</spring-version> </properties> <dependencies> <!-- spring mvc的依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <!-- rest 風格 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.10</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- mybatis spring的插件挽鞠,將mybatis交給spring來管理 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- spring的單元測試 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> </dependency> <!-- spring jdbc,包含事務 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring-version}</version> </dependency> <!-- spring aop的面向切面的配置 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>com.springsource.org.aspectj.weaver</artifactId> <version>1.6.8.RELEASE</version> </dependency> <!-- druid 數(shù)據(jù)源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.28</version> </dependency> <!-- 日志信息 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- junit單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- lombok,特別注意狈孔,與maven的tomcat插件沖突時信认,將scope設置為provided --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> <scope>provided</scope> </dependency> <!-- jsp --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!-- jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <!-- 不過濾java下的.xml文件和.properties配置文件 --> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <!-- define the project compile level --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!-- 添加tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>8081</port> </configuration> </plugin> </plugins> </build> </project>
- 修改 web.xml 內(nèi)容,新增 Spring MVC 和字符編碼過濾器的配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置Spring mvc--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--spring寫好的中文過濾器--> <filter> <filter-name>encode</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
- 在 resources 下新增 SSM 所需的所有的配置文件
- spring-mybatis.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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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 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"> <!-- 引入數(shù)據(jù)庫的配置文件信息 --> <context:property-placeholder location="classpath:db.properties" /> <context:component-scan base-package="com.service" /> <!-- druid數(shù)據(jù)源 --> <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="${url}" /> <property name="driverClassName" value="${driver}" /> <property name="username" value="${user}" /> <property name="password" value="${pass}" /> </bean> <!-- 配置SqlSessionFactoryBean對象均抽,將mybatis交給spring來統(tǒng)一管理嫁赏,獲取SqlSession --> <bean id="sf" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="typeAliasesPackage" value="com.pojo" /> <property name="mapperLocations" value="classpath:com/mapper/*Dao.xml" /> <property name="dataSource" ref="ds" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- 配置映射掃描配置,分別設置dao包掃描和SqlSessionFactory的指定 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name="basePackage" value="com.dao" /> <property name="sqlSessionFactoryBeanName" value="sf" /> </bean> <!-- 配置事務管理器 --> <bean id="dtx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="ds" /> </bean> <!-- 聲明事務的實現(xiàn)方式 以這些關(guān)鍵字開頭的方法分別設置事務的隔離級別以及出錯后的操作--> <tx:advice transaction-manager="dtx" id="tx"> <!-- 聲明屬性油挥,聲明事務規(guī)則 --> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> </tx:attributes> </tx:advice> <!-- 定義切面 --> <aop:config> <aop:pointcut id="mpt" expression="execution(* com.service.*.*(..))" /> <aop:advisor advice-ref="tx" pointcut-ref="mpt" /> </aop:config> </beans>
- spring-mvc.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" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 設置ssm整合項目的注解配置 --> <context:annotation-config /> <!-- 設置包掃描 掃描controller和service包 --> <context:component-scan base-package="com.controller" /> <context:component-scan base-package="com.service" /> <!-- 注解驅(qū)動 --> <mvc:annotation-driven /> <!-- 配置默認資源可以訪問 --> <mvc:default-servlet-handler /> <!-- 引入spring和mybatis的整合文件 --> <import resource="classpath:spring-mybatis.xml" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
- mybatis-config.xml
<?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> <!-- 給當前mybatis項目添加日志功能潦蝇,該STDOUT_LOGGING值的好處是不用添加第三方jar包就可以有日志的輸出 --> <settings> <setting name="logImpl" value="LOG4J"/> </settings> </configuration>
- db.properties
driver = com.mysql.cj.jdbc.Driver url = jdbc:mysql://localhost:3307/school?serverTimezone=UTC user = root pass = 123456 maxActive = 50 minIdle = 1
- log4j.properties
# Global logging configuration log4j.rootLogger = ERROR, stdout, F # MyBatis 日志配置 log4j.logger.com = TRACE # 控制臺輸出 log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %6p [%t] - %m%n log4j.appender.F = org.apache.log4j.DailyRollingFileAppender log4j.appender.F.File = myproj.log log4j.appender.F.Append = true log4j.appender.F.Threshold = DEBUG log4j.appender.F.layout = org.apache.log4j.PatternLayout log4j.appender.F.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss}-[%p %F\:%L] %m%n
- spring-mybatis.xml
- 分別搭建 Spring的單元測試
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring-mybatis.xml") public class TestStudentService { @Autowired private StudentService studentService; @Test public void testService(){ Student s = studentService.queryById(1); System.out.println(s); } }
- 測試 SSM
INFO [main] - {dataSource-1} inited DEBUG [main] - ==> Preparing: select sid, name, pass, tel, addr, age from school.student where sid = ? DEBUG [main] - ==> Parameters: 1(Integer) TRACE [main] - <== Columns: sid, name, pass, tel, addr, age TRACE [main] - <== Row: 1, AAA, 111111, 11111111111, AA, 17 DEBUG [main] - <== Total: 1 com.entity.Student@34f22f9d INFO [Thread-1] - {dataSource-1} closed
- 完成 SSM 的搭建
- SSM 的簡單分頁測試:打開瀏覽器輸入--》http://localhost:8081/student/selectPage
在selectPage后可以加 ?cp=1&ps=3 (數(shù)字可更改)來訪問不同頁數(shù)據(jù)@RestController @RequestMapping("student") public class StudentController { @Resource private StudentService studentService; @GetMapping("selectOne/{id}") public Student selectOne(@PathVariable Integer id) { return this.studentService.queryById(id); } @GetMapping("/selectPage") public List<Student> getStudentsByPage(@RequestParam(value = "cp",defaultValue = "1") int currentPage , @RequestParam(value = "ps",defaultValue = "5") int pageSize){ currentPage = currentPage <= 1 ? 1 : currentPage; pageSize = pageSize <= 0 ? 10 : pageSize; return studentService.queryAllByLimit((currentPage - 1) * pageSize,pageSize); } }