LoginSignup
1
0

More than 1 year has passed since last update.

springKotlinCRUD

Posted at

#spring boot Kotlin CRUD サンプル

testController

@Controller
@RequestMapping("/sample")
class testController {

    @Autowired
    private lateinit var repository: testRepository

    @GetMapping("/form")
    fun form(model: Model, @ModelAttribute("insertCompleteMessage") message: String?): String {
        model.addAttribute("title", "artist name")
        return "form.html"
    }

    @GetMapping("/select")
//    fun select(@Validated searchForm: SearchForm, result: BindingResult, model: Model): String {
    fun select(model: Model): String {
        val list = repository.getPosts("")
        if (list.size != 0) {
            model.addAttribute("postList", list)
        } else {
            model.addAttribute("noResultMessage", "登録はありません。")
        }
        return "list.html"
    }

    /**
     * 新規登録
     */
    @PostMapping("/insert")
    fun insert(
        @Validated insertForm: InsertForm,
        result: BindingResult,
        model: Model,
        redirectAttributes: RedirectAttributes
    ): String {
        if (result.hasErrors()) {
            model.addAttribute("title", "Error Page")
            return "form.html"
        } else if (insertForm.title.isNullOrEmpty()){
            model.addAttribute("message", "※入力必須項目")
            return "form.html"
        }

        val post = convertInsertForm(insertForm)
        repository.insertPost(post)

        return "redirect:select"
    }

    @ModelAttribute
    fun setSearchForm(): SearchForm {
        return SearchForm()
    }

    @ModelAttribute
    fun setInsertForm(): InsertForm {
        return InsertForm()
    }

    /**
     * インサートFormをPostに詰める
     * @param InsertForm
     * @return Post
     */
    companion object {
        fun convertInsertForm(insertForm: InsertForm): Post {
            val post = Post()
            post.title = insertForm.title
            post.textArea = insertForm.textArea
            post.mail = insertForm.mail
            return post
        }
    }
}

testRepository

@Repository
class testRepository {

    @Autowired
    private lateinit var jdbcTemplate: JdbcTemplate

    /**
     * 一覧表示(検索)
     * @param serchStr: String?
     * @return list<Post>
     */
    fun getPosts(serchStr: String?): List<Post> {
        var resultList:List<Map<String,Any?>> = mutableListOf()
        var sql = StringBuilder()
        sql.append("SELECT * FROM post WHERE 1=1 ")
        try {
            if (serchStr.isNullOrEmpty()) {
                resultList = jdbcTemplate.queryForList(sql.toString())
            } else {
                sql.append(" and ( title LIKE '%'||?||'%' or text_area LIKE '%'||?||'%') ")

                resultList = jdbcTemplate.queryForList(sql.toString(), serchStr, serchStr)
            }
        } catch (e:Exception){
            e.printStackTrace()
        }

        val list: MutableList<Post> = ArrayList()
        for (result in resultList) {
            val post = Post()
            post.title = result["title"] as String?
            post.textArea = result["text_area"] as String?
            post.mail = result["mail"] as String?
            list.add(post)
        }
        return list
    }

    /**
     * 新規登録
     */
    fun insertPost(post:Post) {
        val sql = "INSERT INTO post (title,text_area,mail) VALUES (?,?,?)"
        try {
            jdbcTemplate.update(sql, post.title, post.textArea, post.mail)
        } catch (e:Exception) {
            e.printStackTrace()
        }
    }
}

litt.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeLeaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="${title}">Insert</title>
</head>
<body>
<h1 th:text="${title}">title</h1>
<h1 th:text="${redirectTitle}">title</h1>
<form method="GET" action="#" th:action="@{/sample/select}" th:object="${searchForm}">
    <label for="artistName">検索</label>
    <input id="artistName" name="artistName" type="text" th:value="*{artistName}">
    <div th:if="${#fields.hasErrors('artistName')}" th:errors="*{artistName}"></div>
    <input type="submit" value="search">
</form>

<!--<h1 th:text="${title}">title</h1>-->
<p th:text="${noResultMessage}"></p>
<table th:if="${postList}">
    <tr>
        <th>タイトル</th><th>内容</th><th>mail</th>
    </tr>
    <tr th:each="post:${postList}">
        <td th:text="${post.title}"></td>
        <td th:text="${post.textArea}"></td>
        <td th:text="${post.mail}"></td>
    </tr>
</table>
<a th:href="@{'/sample/form'}">新規登録</a>
</body>

form.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeLeaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="${title}"></title>
</head>
<body>
<h1>新規登録</h1>
<form method="POST" action="#" th:action="@{/sample/insert}" th:object="${insertForm}">
    <div>
    <label for="title">タイトル</label>
    <input id="title" name="title" type="text" th:value="*{title}"><span th:text="${message}"></span>
    <div th:if="${#fields.hasErrors('title')}" th:errors="*{title}"></div>
    </div>
    <div>
    <input id="textArea" name="textArea" type="textarea" th:value="*{textArea}">
    </div>
    <div>
    <label for="mail">mail:</label>
    <input id="mail" name="mail" type="text" th:value="*{mail}">
    </div>
    <input type="submit" value="insert">
</form>
<p th:text="${insertCompleteMessage}"></p>
<p th:if="${errorMessage}" th:text="'エラーメッセージ:'+${errorMessage}"></p>
</body>
</html>

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0