Java学习 http://blog.okbase.net/javaeye 添加国内镜像站解决maven 在intellij IDEA 下载依赖包速度慢的问题 http://blog.okbase.net/javaeye/archive/56453.html javaeye 2020-5-21 23:12:00 File->Settings->Build,Execution,eployment->Build Tools->Maven
右边找到User settings file,打钩Override,找到编辑框里的文件settings.xml(如果没有,则手工创建一个)
然后把如下代码粘贴进去,重启IDE就可以了。

 

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <mirrors>
        <!-- mirror
         | Specifies a repository mirror site to use instead of a given repository. The repository that
         | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
         | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
         |
        <mirror>
          <id>mirrorId</id>
          <mirrorOf>repositoryId</mirrorOf>
          <name>Human Readable Name for this Mirror.</name>
          <url>http://my.repository.com/repo/path</url>
        </mirror>
         -->

        <mirror>
            <id>alimaven</id>
            <name>aliyun maven</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <mirrorOf>central</mirrorOf>
        </mirror>

        <mirror>
            <id>nexus-163</id>
            <mirrorOf>*</mirrorOf>
            <name>Nexus 163</name>
            <url>http://mirrors.163.com/maven/repository/maven-public/</url>
        </mirror>
        
        <mirror>
            <id>nexus</id>
            <name>internal nexus repository</name>
            <url>http://repo.maven.apache.org/maven2</url>
            <mirrorOf>central</mirrorOf>
        </mirror>

    </mirrors>
</settings>
]]>
Mybatis入门学习记录 http://blog.okbase.net/javaeye/archive/56452.html javaeye 2020-5-19 22:21:00 1.POM里添加依赖

<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.5.4</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.11</version>
</dependency>
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.18.12</version>
	<scope>provided</scope>
</dependency>

在<build></build>里面添加:

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>


否则,包里面的xml文件无法读取,会显示错误:Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/huawei/testdemo/repository/UserRepository.xml


2.数据库里添加数据表
CREATE TABLE `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(20) CHARACTER SET utf8 NOT NULL,
`age` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB

 

3.实体类(依赖lombok)
创建类com.huawei.testdemo.entity.User

import lombok.Data;

@Data
public class User {
    private long id;
    private String username;
    private int age;
}

 

4.创建MyBatis配置文件config.xml 配置MyBatis运行环境

配置JDBC事务管理(类型为JDBC):
<transactionManager type="JDBC"></transactionManager>

 

配置JDBC数据源连接池(类型为POOLED):

<dataSource type="POOLED">
    <property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"></property>
    <property name="username" value="root"></property>
    <property name="password" value="123456"></property>
</dataSource>

5.持久层接口
5.1 使用原生接口(不推荐,略)
自定义SQL语句,写在Mapper.xml文件里。
为每个实体类创建对应的Mapper.xml,例如UserMapper.xml
在config.xml里注册该例如UserMapper.xml

5.2 代理接口
创建类repository.UserRepository

public interface UserRepository {
    public int save(User user);
    public int update(User user);
    public int deleteById(long id);
    public List<User> findAll();
    public List<User> findByUser();
}

mapper映射文件UserRepository.xml

<insert id="save" parameterType="com.huawei.testdemo.entity.User">
    insert into users(username,age) values(#{username},#{age})
</insert>
<update id="update" parameterType="com.huawei.testdemo.entity.User">
    update users
    <set>
        <if test="username!=null">
            username = #{username},
        </if>
        <if test="age!=0">
            age = #{age}
        </if>
    </set>
    where id = #{id}
</update>

<delete id="deleteById" parameterType="long">
    delete from users where id = #{id}
</delete>
<select id="findAll" resultType="com.huawei.testdemo.entity.User">
    select * from users
</select>
<select id="findByUser" parameterType="com.huawei.testdemo.entity.User" resultType="com.huawei.testdemo.entity.User">
select * from users
<where>
    <choose>
        <when test="id!=0">
            id = #{id}
        </when>
        <when test="username!=null">
            and username = #{username}
        </when>
        <when test="age!=0">
            and age = #{age}
        </when>
    </choose>
</where>
</select>

-------------------
6.代码

InputStream inputStream = ResolverUtil.Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
String statement = "com.huawei.testdemo.repository.UserRepository.save";
User user = new User("小陈", 23);
sqlSession.insert(statement, user);
sqlSession.commit();
sqlSession.close();

--------------------------
错误信息:
Error updating database. Cause: 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.
### The error may exist in com/huawei/testdemo/repository/UserRepository.xml

 

解决方案:
1)修改数据库变量
mysql> set global time_zone='+8:00';

2)连接MySQL时,指定时区为UTC
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"></property>
--------------------------

学习视频:https://www.bilibili.com/video/BV1V7411w7VW

]]>
SpringBoot thymeleaf的第一次使用 http://blog.okbase.net/javaeye/archive/56447.html javaeye 2020-5-16 18:41:00 一、添加依赖

pom.xml里面添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

二、使用Model进行传值
控制器里:

@Controller
@RequestMapping("/test")
public class TestController {
    @RequestMapping("/hello")
    public String hello(Model model)
    {
        model.addAttribute("name", "小张");
        return "test/hello";
    }
}

 

 

三、模板文件

页面模板文件默认放置在resources/templates目录下,本例中控制器中返回"test/hello",实际使用的模板文件为:resources/templates/test/hello.html

 

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>thymeleaf测试</title>
</head>
<body>
<h2 th:text="'hello '+${name}"></h2>
</body>
</html>

 

运行后调用localhost/test/hello 页面输出 hello 小张

 

关于thymeleaf详细的文档,可以参阅官方网站文档:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

]]>
springboot项目报错:There was an unexpected error (type=Not Found, status=404) http://blog.okbase.net/javaeye/archive/56446.html javaeye 2020-5-16 14:41:00 错误信息:

This application has no explicit mapping for /error, so you are seeing this as a fallback.

 

Sat Day 16 18:21:38 CST 2020
There was an unexpected error (type=Not Found, status=404).
No message available

 

经检查,发现TestController这个Controller没有正确放到com.xxx.testdemo这个包下面导致的,
控制器和主程序不在同一个包下,当然会出现Not Found 404的错误。

]]>
使用Spring Initializr快速新建SpringBoot项目 http://blog.okbase.net/javaeye/archive/56445.html javaeye 2020-5-14 20:20:00 一、新建Maven工程

IDEA菜单 File->New->Project->Spring Initializr->默认值,点击Next

Group填组织(公司)名称,例如:com.huawei
Artifact填工程名称,例如:sprintboot-test
Type:Maven Project
Language: Java
Packaging:Jar
Java Version:8
Version:项目版本
Name:项目名称
Description:描述
Package:包名

选择依赖Dependencies,例如Web->Sprint Web,点击Next

输入项目名和项目位置,点击Finish完成。

 

二、Controller和Service
主程序已经自动建好了,接下来就是添加控制器和实现业务逻辑了。
右键点com.test,菜单,新建-Java类,命名为HomeController,添加Controller注解。
添加hello方法,并添加RequestMapping和ResponseBody注解,
代码里没有其它业务逻辑,只是简单地返回字符串,代码如下:

@Controller
public class HomeController {
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "Hello world";
    }

    @RequestMapping("/")
    @ResponseBody
    public String home(){
        return "Home page";
    }
}

 

三、运行测试
打开主程序HelloWorldMainApplication.java,在main处,点左边的绿色运行按钮,会自动编译,并自动打开Apache Tomcat。
console窗口显示:
Tomcat started on port(s): 8080 (http) with context path ''
Started HelloWorldMainApplication in 1.171 seconds (JVM running for 1.665)
Initializing Spring DispatcherServlet 'dispatcherServlet'
Initializing Servlet 'dispatcherServlet'
Completed initialization in 4 ms

说明程序已经启动,我们打开浏览器,访问 http://localhost:8080/hello 测试结果。

 

四、编译打包部署
maven是通过pom.xml来执行任务的.其中的build标签描述了如何来编译打包项目,而具体的编译和打包工作是通过build中配置的plugin来完成的。Spring Initializr已经在pom.xml里为我们添加好了。

IDEA最右侧打开Maven,在Lifecycle里,选中package,点Run maven build按钮,开始编译生成,
Building jar: E:\IdeaProjects\testdemo\target\testdemo-0.0.1-SNAPSHOT.jar

最后显示:BUILD SUCCESS

在E:\IdeaProjects\testdemo\target目录下,我们执行
java -jar helloworld-1.0-SNAPSHOT.jar --server.port=80
就可以启动应用,这里指定80端口运行,默认是8080。
我们在application.properties里添加server.port=80,可以指定端口为80,这样就不用在运行的时候添加--server.port=80来指定了。

 

五、目录结构
Resources目录下文件:static文件夹:存储静态资源文件,如js/css/images;
templates文件夹:保存所有的模板页面;
application.properties文件:spring boot的默认配置文件,可以修改一些Server,cookie、session、ssl、tomcat的默认配置;
例如:
server.address #指定server绑定的地址
server.compression.enabled #是否开启压缩,默认为false.
server.port #设定http监听端口
server.session.cookie.domain #指定session cookie的domain
server.session.cookie.max-age #设定session cookie的最大age.
server.session.timeout #session的超时时间
server.ssl.enabled #是否开启ssl,默认: true
server.tomcat.accesslog.enabled #是否开启access log,默认: false
server.tomcat.max-threads #设定tomcat的最大工作线程数,默认为: 0

 

 

]]>
使用IDEA开发第一个SpringBoot应用HelloWorld http://blog.okbase.net/javaeye/archive/56440.html javaeye 2020-5-10 21:19:00 本文配套的源代码:http://www.okbase.net/file/item/34710

 

一、新建maven工程

菜单->File->New->Project->Maven


二、导入SpringBoot相关依赖
打开pom.xml,添加:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

当前最新版本是2.2.7.RELEASE,可以到https://spring.io/projects/spring-boot#learn 查看最新的版本。

如果未配置自动导入,可以右键点pom.xml,选择->Maven->Reimport

 

三、主程序
在src->main->java处右键菜单,新建-Java类,命名为com.test.HelloWorldMainApplication,
psvm快捷键添加main方法,添加Spring应用运行代码,并添加@SpringBootApplication注解,代码如下:

@SpringBootApplication
public class HelloWorldMainApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloWorldMainApplication.class, args);
    }
}

 

四、Controller和Service
右键点com.test,菜单,新建-Java类,命名为HomeController,添加Controller注解。
添加hello方法,并添加RequestMapping和ResponseBody注解,
代码里没有其它业务逻辑,只是简单地返回字符串,代码如下:

@Controller
public class HomeController {
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "Hello world";
    }

    @RequestMapping("/")
    @ResponseBody
    public String home(){
        return "Home page";
    }
}

 

五、运行测试
打开主程序HelloWorldMainApplication.java,在main处,点左边的绿色运行按钮,会自动编译,并自动打开Apache Tomcat。
console窗口显示:
Tomcat started on port(s): 8080 (http) with context path ''
Started HelloWorldMainApplication in 1.171 seconds (JVM running for 1.665)
Initializing Spring DispatcherServlet 'dispatcherServlet'
Initializing Servlet 'dispatcherServlet'
Completed initialization in 4 ms

说明程序已经启动,我们打开浏览器,访问 http://localhost:8080/hello 测试结果。

 

六、编译打包部署
maven是通过pom.xml来执行任务的.其中的build标签描述了如何来编译打包项目,而具体的编译和打包工作是通过build中配置的plugin来完成的。
pom.xml里添加
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

 

IDEA最右侧打开Maven,在Lifecycle里,选中package,点Run maven build按钮,开始编译生成,
Building jar: E:\IdeaProjects\helloworld\target\helloworld-1.0-SNAPSHOT.jar

最后显示:BUILD SUCCESS

在E:\IdeaProjects\helloworld\target目录下,我们执行
java -jar helloworld-1.0-SNAPSHOT.jar --server.port=80
就可以启动应用,这里指定80端口运行,默认是8080。

 

]]>