spring boot學習(四)之連線資料庫jdbcTemplate動態取資料
新增資料庫依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
在 application.properties
配置檔案中配置資料來源
spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 spring.datasource.username = root spring.datasource.password = 123456 spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
新增資料池依賴,這裡用的是阿里巴巴的資料池
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.19</version> </dependency>
在啟動類 Chapter1Application.java
中讀取資料來源配置資訊,Spring Boot會自動的用我們配置的這個DataSource。新增如下程式碼
@Autowired private Environment environment; public DataSource dataSource(destroyMethod ="close") { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(environment.getProperty("datasource.url")); dataSource.setUsername(environment.getProperty("datasource.username")); dataSource.setPassword(environment.getProperty("datasource.password")); dataSource.setDriverClassName(environment.getProperty("datasource.driver-class-name")); dataSource.setInitialSize(5);//初始化時建立物理連線的個數 dataSource.setMaxActive(20);//最大連線池數量 dataSource.setMinIdle(0);//最小連線池數量 dataSource.setMaxWait(50000);//獲取連線時最大等待時間,單位毫秒。 dataSource.setValidationQuery("SELECT 1");//用來檢測連線是否有效的sql return dataSource; }
下面就用我們配置的這個資料來源資訊,用JdbcTemplate來與資料庫進行資料互動
本地建立 spring
資料庫,再建立一張 user
表,表屬性如下,自行填幾條資料:

1.png
簡單的做了個查詢的例子:
建立實體檔案: User.java
public class User { private int id; private String name; private int age; private String address; private String phone; //set and get }
controller
層: UserController.java
:
@RestController public class UserController { @Autowired private UserService userService; private Logger logger = LoggerFactory.getLogger(this.getClass()); @RequestMapping(value = "/queryUserList",method = RequestMethod.GET,produces="application/json;charset=UTF-8") @ResponseBody public String queryLearnList(HttpServletRequest request , HttpServletResponse response){ String name = request.getParameter("name"); String phone = request.getParameter("phone"); Map<String,Object> params = new HashMap<String,Object>(); params.put("name", name); params.put("phone", phone); List userList =userService.queryUserList(params); return JSONArray.fromObject(userList).toString(); }
service
層:介面 UserService.java
和實現類 UserServiceImpl.java
public interface UserService { List queryUserList(Map<String, Object> params); }
@Service public class UserServiceImpl implements UserService { @Autowired UserDao userDao; @Override public List queryUserList(Map<String,Object> params) { return userDao.queryUserList(params); } }
dao
層:介面 UserDao.java
和實現類 UserDaoImpl.java
public interface UserDao { public List queryUserList(Map<String, Object> params); }
UserDaoImpl .java
注入 JdbcTemplate
,spring boot會自動選擇我們配置好的資料來源:
@Repository public class UserDaoImpl implements UserDao{ @Autowired private JdbcTemplate jdbcTemplate;//這裡直接引用即可 @Override public List queryUserList(Map<String, Object> params) { StringBuffer sql =new StringBuffer(); sql.append("select * from user where 1=1"); if(!StringUtil.isNull((String)params.get("name"))){ sql.append(" and name like '%").append((String)params.get("name")).append("%'"); } if(!StringUtil.isNull((String)params.get("phone"))){ sql.append(" and phone like '%").append((String)params.get("phone")).append("%'"); } List<User> list = jdbcTemplate.query(sql.toString(),new BeanPropertyRowMapper(User.class)); return list; } }
結果
執行專案,瀏覽器輸入: http://localhost:8080/queryUserList
,得到如下結果

1.png
總結
在此實踐過程可能會出現以下問題:
第一個錯誤
報錯資訊
:

1.png
原因
:專案打了jar包,一旦執行就會有兩個啟動類,指定其中一個即可
解決辦法
:在pom.xml的plugin下面新增如下配置即可
<configuration> <mainClass>com.mlin.ChapterApplication</mainClass> </configuration>
第二個錯誤
報錯資訊:
java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
原因
:沒有配置時區資訊
解決辦法
:在配置資料來源的時候加上 serverTimezone=GMT%2B8
datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
第三個錯誤
報錯資訊
:就是在用到 return JSONArray.fromObject(userList).toString();
時,引入 net.sf.json-lib
依賴一直引入不進去
原因
:要指定jdk
解決辦法
:加入 <classifier>jdk15</classifier>
即可,但是改成jdk8或是jdk7不行:
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>
原創作者:夢凌小樣
作品連結: ofollow,noindex">https://www.jianshu.com/p/45eb56f448ae 【原創不易,轉載請註明出處,感謝理解】
一位愛生活,愛創作,愛分享,愛自己的90後女程式員一枚,記錄工作中的點點滴滴,一起學習,共同進步,期待能和優秀的您交上朋友