idea軟件spring boot+jpa問題總結

yml配置文件:

#配置jpa
jpa:
    database: MySQL
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true
    hibernate:
      ddl-auto: update  

ddl-auto:主要存在四種屬性:create,create-drop,update和validate

ddl-auto:create ----每次運行該程序,沒有表格會新建表格,表內有數據會清空;
ddl-auto:create-drop ----每次程序結束的時候會清空表
ddl-auto:update ---- 每次運行程序,沒有表格會新建表格,表內有數據不會清空,只會更新
ddl-auto: validate ---- 運行程序會校驗數據與數據庫的字段類型是否相同,不同會報錯。
-------------------

1、實體類添加@Entity @Table

@Table(name="userinfo")// 這個名字會在你的數據庫自動生成,所以只需要自己創建好數據庫,然後jpa會自動生成。

如下:

 @Id
 @GeneratedValue
 @Column(name = "Id")
 private int Id;
 @Column(name = "Name")
 private String Name;
 @Column(name = "Age")
 private int Age;

然後添加get ,set 方法及其構造方法

---------------------------

package com.springboot_jpa.demo.Repository;

import com.springboot_jpa.demo.entity.UserInfo;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;

@Configuration 
@Repository
@Transactional  //事務
public interface uersRepository extends JpaRepository<UserInfo,Long> {
    @Override
    <S extends UserInfo> S saveAndFlush(S s);

    /**
     * 查詢全部
    * */
//        @Query("from userInfo")
//        public UserInfo getUerInfo(@Param("Id") Integer id,@Param("Name") String Name,@Param("Age") Integer Age);
    /**
     * 模糊查詢
     * */
    /**
     * 添加用戶
     * */
    //可以自己手動寫sql
   // public UserInfo AddUerInfo(@Param("Id") Integer id, @Param("Name") String Name, @Param("Age") Integer Age);
    //@Modifying
    @Query(value = "Insert into  userInfo(Name,Age) value(?,?)",nativeQuery = true)
    void AddUerInfo(String name, int age);

    /**
     * 用戶修改
     * */
   
    /**
     * 刪除用戶
     * */
 @Modifying
    @Query(value = "delete from userInfo where Id=? ",nativeQuery = true)
    void deleteById(int Id);
}

-------------------------

service層:

  //添加用戶
    @Override
    @Transactional
    public void addUserInfo(UserInfo user) {   
      String string=uersRepository.saveAndFlush(user).toString();
       System.out.println("結果:"+string);
    }

---------------------------

controller層:

 @ResponseBody
    @GetMapping("/save")
    public JSONObject save(@RequestParam("name") String Name, @RequestParam("age") Integer Age) {
        UserInfo user = new UserInfo();
        user.setName(Name);
        user.setAge(Age);
        UserInfoServiceImpl.addUserInfo(user);

        JSONObject jsonObject = UserInfoServiceImpl.getAllUserInfo();
        System.out.println("查詢全部:" + jsonObject.toString());
        return jsonObject;

    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章