当前位置:网站首页>SSM integration example
SSM integration example
2022-07-26 20:52:00 【Bai Xiaoyun】
SSM Integrate
technological process :
1. Create a project
2.SSM Integrate
Spring:
SpringConfig
@Configuration @ComponentScan("com.aiit.service") @PropertySource("classpath:jdbc.properties") @Import({ JdbcConfig.class,MybatisConfig.class}) public class SpringConfig { }
MyBatis:
- MyBatisConfig
public class MybatisConfig {
// Set the two bean
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.aiit.domain");
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer=new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.aiit.dao");
return mapperScannerConfigurer;
}
}
- JdbcConfig
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
DruidDataSource druidDataSource=new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
}
- jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.username=root
jdbc.password=20020630
SpringMVC:
- ServletConfig
public class ServletContainsConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{
SpringConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{
SpringMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{
"/"};
}
}
- SpringMvcConfig
@Configuration
@ComponentScan("com.aiit.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
3. Function module
Table and entity classes
dao( Interface + Automatic agent )
public interface BookDao {
// newly added
@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
public void save(Book book);
// modify
@Update("update tbl_book set type=#{type},name=#{name},description=#{description} where id=#{id}")
public void update(Book book);
// Delete
@Delete("delete from tbl_book where id=#{id}")
public void delete(Integer id) ;
// according to id Inquire about
@Select("select * from tbl_book where id=#{id}")
public Book selectById(Integer id);
@Select("select * from tbl_book")
// Query all
public List<Book> selectAll();
}
service( Interface + Implementation class )
- Business layer interface test
public interface BookService {
// newly added
public boolean save(Book book);
// modify
public boolean update(Book book);
// Delete
public boolean delete(Integer id) ;
// according to id Inquire about
public Book selectById(Integer id);
// Query all
public List<Book> selectAll();
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public boolean save(Book book) {
bookDao.save(book);
return true;
}
@Override
public boolean update(Book book) {
bookDao.update(book);
return true;
}
@Override
public boolean delete(Integer id) {
bookDao.delete(id);
return true;
}
@Override
public Book selectById(Integer id) {
return bookDao.selectById(id);
}
@Override
public List<Book> selectAll() {
return bookDao.selectAll();
}
}
controller
- Presentation layer interface testing
@Controller
@ResponseBody
@RequestMapping("/books")
public class BookContorller {
@Autowired
private BookService bookService;
@PostMapping
public boolean save(@RequestBody Book book) {
bookService.save(book);
return true;
}
@PutMapping
public boolean update(@RequestBody Book book) {
bookService.update(book);
return true;
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
bookService.delete(id);
return true;
}
@GetMapping("/{id}")
public Book selectById(@PathVariable Integer id) {
return bookService.selectById(id);
}
@GetMapping
public List<Book> selectAll() {
return bookService.selectAll();
}
}
4. Transaction processing
1. Configure that the current interface method has a transaction
Use @Transactional annotation
@Transactional
public interface BookService {
// newly added
public boolean save(Book book);
// modify
public boolean update(Book book);
// Delete
public boolean delete(Integer id) ;
// according to id Inquire about
public Book selectById(Integer id);
// Query all
public List<Book> selectAll();
}
2. Configure transaction manager
Use formal parameter injection dataSource
stay jdbcConfig Class
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
3. Enable annotated transaction driven
stay SpringConfig in
@EnableTransactionManagement
5. Realization Presentation layer and front-end data transmission protocol
Define the return result class
public class Result {
private Object data;
private Integer code;
private String msg;
// Provide construction method
public Result() {
}
public Result(Object data, Integer code) {
this.data = data;
this.code = code;
}
public Result(Object data, Integer code, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Definition Code class
public class Code {
public static final Integer SAVE_OK=20011;
public static final Integer DELETE_OK=20021;
public static final Integer UPDATE_OK=20031;
public static final Integer GET_OK=20041;
public static final Integer SAVE_ERR=20010;
public static final Integer DELETE_ERR=20020;
public static final Integer UPDATE_ERR=20030;
public static final Integer GET_ERR=20040;
}
Modify presentation layer BookController The return value of
@Controller
@ResponseBody
@RequestMapping("/books")
public class BookContorller {
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book) {
boolean flag = bookService.save(book);
return new Result(flag,flag?Code.SAVE_OK:Code.SAVE_ERR);
}
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag = bookService.update(book);
return new Result(flag,flag?Code.UPDATE_OK:Code.UPDATE_ERR);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
boolean flag = bookService.delete(id);
return new Result(flag,flag?Code.DELETE_OK:Code.DELETE_ERR);
}
@GetMapping("/{id}")
public Result selectById(@PathVariable Integer id) {
Book book = bookService.selectById(id);
return new Result(book,book==null?Code.GET_ERR:Code.GET_OK,book==null?" Data query failed ":" The query is successful ");
}
@GetMapping
public Result selectAll() {
List<Book> books = bookService.selectAll();
return new Result(books,books==null?Code.GET_ERR:Code.GET_OK,books==null?" Data query failed ":" The query is successful ");
}
}
6. exception handling
Define a system exception class inheritance RuntimeException
public class BusinessExcpetion extends RuntimeException {
private Integer code;
public BusinessExcpetion(Integer code) {
this.code = code;
}
public BusinessExcpetion(String message, Integer code) {
super(message);
this.code = code;
}
public BusinessExcpetion(String message, Throwable cause, Integer code) {
super(message, cause);
this.code = code;
}
public BusinessExcpetion(Throwable cause, Integer code) {
super(cause);
this.code = code;
}
public BusinessExcpetion(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
Define a business exception class
public class BusinessExcpetion extends RuntimeException {
private Integer code;
public BusinessExcpetion(Integer code) {
this.code = code;
}
public BusinessExcpetion(String message, Integer code) {
super(message);
this.code = code;
}
public BusinessExcpetion(String message, Throwable cause, Integer code) {
super(message, cause);
this.code = code;
}
public BusinessExcpetion(Throwable cause, Integer code) {
super(cause);
this.code = code;
}
public BusinessExcpetion(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
Customize an exception handling class in the presentation layer , Used to catch exceptions in the program
We make an exception
@Override
public Book selectById(Integer id) {
// Make an exception to act as a business exception
if (id==100){
throw new BusinessExcpetion(" Please don't challenge my patience with your skills !", Code.BUSINESS_ERR);
}
return bookDao.selectById(id);
}
When the query id yes 100 when , Return business exception

Loading page
1. release
Configure a class inheritance WebMvcConfigurationSupport
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
}
Release resources, otherwise you will not be able to access resources
To be in SpringMvcConfig Scan the configuration class
The code implementation of the front end :
<!DOCTYPE html>
<html>
<head>
<!-- page meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SpringMVC Case study </title>
<meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
<!-- Introducing styles -->
<link rel="stylesheet" href="../plugins/elementui/index.css">
<link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="../css/style.css">
</head>
<body class="hold-transition">
<div id="app">
<div class="content-header">
<h1> Book management </h1>
</div>
<div class="app-container">
<div class="box">
<div class="filter-container">
<el-input placeholder=" The name of the book " v-model="pagination.queryString" style="width: 200px;" class="filter-item"></el-input>
<el-button @click="getAll()" class="dalfBut"> Inquire about </el-button>
<el-button type="primary" class="butT" @click="handleCreate()"> newly build </el-button>
</div>
<el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
<el-table-column type="index" align="center" label=" Serial number "></el-table-column>
<el-table-column prop="type" label=" Book category " align="center"></el-table-column>
<el-table-column prop="name" label=" The name of the book " align="center"></el-table-column>
<el-table-column prop="description" label=" describe " align="center"></el-table-column>
<el-table-column label=" operation " align="center">
<template slot-scope="scope">
<el-button type="primary" size="mini" @click="handleUpdate(scope.row)"> edit </el-button>
<el-button type="danger" size="mini" @click="handleDelete(scope.row)"> Delete </el-button>
</template>
</el-table-column>
</el-table>
<!-- Add tag layer -->
<div class="add-form">
<el-dialog title=" New books " :visible.sync="dialogFormVisible">
<el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label=" Book category " prop="type">
<el-input v-model="formData.type"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label=" The name of the book " prop="name">
<el-input v-model="formData.name"/>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label=" describe ">
<el-input v-model="formData.description" type="textarea"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false"> Cancel </el-button>
<el-button type="primary" @click="handleAdd()"> determine </el-button>
</div>
</el-dialog>
</div>
<!-- Edit label layer -->
<div class="add-form">
<el-dialog title=" Edit check item " :visible.sync="dialogFormVisible4Edit">
<el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label=" Book category " prop="type">
<el-input v-model="formData.type"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label=" The name of the book " prop="name">
<el-input v-model="formData.name"/>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label=" describe ">
<el-input v-model="formData.description" type="textarea"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible4Edit = false"> Cancel </el-button>
<el-button type="primary" @click="handleEdit()"> determine </el-button>
</div>
</el-dialog>
</div>
</div>
</div>
</div>
</body>
<!-- Import component library -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script> var vue = new Vue({
el: '#app', data:{
pagination: {
}, dataList: [],// List data to be displayed on the current page formData: {
},// The form data dialogFormVisible: false,// Controls whether the form is visible dialogFormVisible4Edit:false,// Edit whether the form is visible rules: {
// Validation rules type: [{
required: true, message: ' Book category is required ', trigger: 'blur' }], name: [{
required: true, message: ' Book name is required ', trigger: 'blur' }] } }, // Hook function ,VUE Automatically execute after object initialization created() {
this.getAll(); }, methods: {
// list getAll() {
// Query all axios.get("/books").then((resp)=>{
this.dataList=resp.data.data; }) }, // Pop up add window handleCreate() {
this.dialogFormVisible=true; }, // Reset form resetForm() {
this.formData={
}; }, // add to handleAdd () {
this.resetForm(); axios.post("/books",this.formData).then((resp)=>{
// After sending the request , Hide the dialog if (resp.data.code==20011){
this.dialogFormVisible=false; // Refresh the page this.$message({
message: ' congratulations , Add success ', type: 'success' }); this.getAll(); } else if (resp.data.code==20010){
// Pop up a pop-up dialog box to prompt error ' this.$message.error(' Add failure '); } else{
// this.$message.error(resp.data.msg); } }) }, // The edit window pops up handleUpdate(row) {
this.dialogFormVisible4Edit=true; axios.get("/books/"+row.id).then((resp)=>{
this.formData=resp.data.data; }) }, // Click the edit button handleEdit() {
this.formData=""; axios.put("/books", this.formData).then((res)=> {
// If the operation is successful if(res.data.code == 20031) {
this.dialogFormVisible4Edit = false; this.$message.success(" Modification successful "); } else if (resp.data.code==20030){
// Pop up a pop-up dialog box to prompt error ' this.$message.error(' Modification failed '); } else{
// this.$message.error(resp.data.msg); } }).finally(()=>{
this.getAll(); }) }, // Delete handleDelete(row) {
// Pop-up dialog box this.$confirm(' This operation will permanently delete the column data , Whether or not to continue ?', ' Tips ', {
confirmButtonText: ' determine ', cancelButtonText: ' Cancel ', type: 'warning' }).then(() => {
axios.delete("/books/"+row.id).then((resp)=>{
if(resp.data.code==20021) {
this.$message({
type: 'success', message: ' Delete successful !' }); } else if (resp.data.code==20030){
// Pop up a pop-up dialog box to prompt error ' this.$message.error(' Delete failed '); } else{
// this.$message.error(resp.data.msg); } }).finally(()=>{
this.getAll(); }) }).catch(() => {
this.$message({
type: 'info', message: ' Delete cancelled ' }); }); } } }) </script>
</html>
边栏推荐
- Solve the horizontal segmentation of iBGP and BGP routing principles
- Kotlin - coroutinecontext
- LeetCode链表问题——19.删除链表的倒数第N个节点(一题一文学会链表)
- Leetcode刷题之——链表总结
- Applied materials announced that it would acquire international electric with us $2.2 billion in cash
- What is the role of cache in the storage system of data blocks?
- 英国德国相继推出5G商用服务,华为成幕后功臣
- 81.(cesium之家)cesium修改灰色背景(默认蓝色)
- Experiment 6 BGP federal comprehensive experiment
- leetcode 链表类
猜你喜欢

How to assemble a registry?

易基因|宏病毒组测序技术介绍

QT signal and slot connection (loose coupling)

Buu brush inscription - WANGDING cup column 2
![[interview brush 101] dynamic planning 1](/img/aa/cf9326d0a4363e96f4e2f1c6079c13.png)
[interview brush 101] dynamic planning 1

实验6 BGP联邦综合实验

Solve the horizontal segmentation of iBGP and BGP routing principles

Experiment 5 OSPF comprehensive experiment
![[experiment sharing] CCIE BGP routing black hole experiment]](/img/c8/7ccb879ad7c739d3573637fd14f4e1.png)
[experiment sharing] CCIE BGP routing black hole experiment]

Bean注入和生命周期
随机推荐
[英雄星球七月集训LeetCode解题日报] 第26日 并查集
Kotlin - coroutinecontext
Houdini 笔记2
884. 两句话中的不常见单词-哈希表
Opencv DNN deployment onnx model
Leetcode's question brushing -- List summary
A super simple neural network code with 5 coordinates for one layer node training
Basic configuration and aggregation of BGP
Chat software project development 2
Swiftui 4's new function of real-time access to click location.Ontapgeture {location in} (tutorial with source code)
剑指offer46把数字翻译成字符串
ST表、带权并查集
执行上下文与词法环境
Shell综合应用案例,归档文件
Confid+etcd to realize automatic discovery of high availability
Solve the horizontal segmentation of iBGP and BGP routing principles
Correct the classpath of your application so that it contains compatible versions of the classes com
Buu brush inscription - WANGDING cup column 2
How to praise others gracefully? Try these methods
Execution context and Lexical Environment