For 8.0.12 and earlier: Use SSL when communicating with the server (true/false), default is ‘true’ when connecting to MySQL 5.5.45+, 5.6.26+ or 5.7.6+, otherwise default is ‘false’.
For 8.0.13 and later: Default is ‘true’. DEPRECATED. See sslMode property description for details.
Default Value: true
Since Version: 3.0.2
autoReconnect
Should the driver try to re-establish stale and/or dead connections
Default Value: false
Since Version: 1.1
maxReconnects
Maximum number of reconnects to attempt if autoReconnect is true, default is ‘3’.
useSSL=true autoReconnect=true
Others
Timeout
initialTimeout
If autoReconnect is enabled, the initial time to wait between re-connect attempts (in seconds, defaults to ‘2’).
Default Value: 2
Since Version: 1.1
connectTimeout
Timeout for socket connect (in milliseconds), with 0 being no timeout. Only works on JDK-1.4 or newer. Defaults to ‘0’.
Default Value: 0
Since Version: 3.0.1
socketTimeout
Timeout (in milliseconds) on network socket operations (0, the default means no timeout).
Using MyBatis to query DATETIME type column data from MySQL table, if the column value is 0000-00-00 00:00:00, the program will throw exception Java.sql.SQLException. The following are the column properties.
pubtime DATETIME NULLDEFAULTNULL
Error Info
Error attempting to get column 'pubtime' from result set. Cause: java.sql.SQLException: Zero date value prohibited ; Zero date value prohibited; nested exception is java.sql.SQLException: Zero date value prohibited org.springframework.dao.TransientDataAccessResourceException: Error attempting to get column 'pubtime' from result set. Cause: java.sql.SQLException: Zero date value prohibited ; Zero date value prohibited; nested exception is java.sql.SQLException: Zero date value prohibited
Solutions
To set up zeroDateTimeBehavior=convertToNull in JdbcUrl. zeroDateTimeBehavior values can be EXCEPTION, ROUND, and CONVERT_TO_NULL. The default value of zeroDateTimeBehavior is EXCEPTION.
Using @Component inject the bean to the Spring IoC container.
Using @Value read application configurations of Spring into non-static fields.
Implements InitializingBean override afterPropertiesSet() method. Assigning non-static field values to static field values in afterPropertiesSet() method.
Compare date in where clauses of MyBatis mapper XML query.
<iftest="beginTime != null and beginTime != ''"> createTime >= #{beginTime} and </if>
Error Info
nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String ### Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String ### Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String
Solutions
remove beginTime != '' in the <if> element of MyBatis mapper XML file.
<iftest="beginTime != null"> createTime >= #{beginTime} and </if>
Reasons
When you pass Date objects as a parameter to MyBatis mapper XML query, you can’t compare the Date object with a String object in MyBatis <if> elements.
@Deprecated// programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. @FunctionalInterface @Override// Indicates that a method declaration is intended to override a method declaration in a supertype. @SuppressWarnings// Indicates that the named compiler warnings should be suppressed in the annotated element (and in all program elements contained in the annotated element). @SafeVarargs// A programmer assertion that the body of the annotated method or constructor does not perform potentially unsafe operations on its varargs parameter.
Spring Projects
Spring
Bean declaration
@Component @Controller @Service @Repository
Make a bean belong to a particular profile
@Profile("dev")
@Profile({"dev","test"})
// Only can contains one !string. Can't be like {"!dev","!test"} @Profile("!dev")
@PathVariable @RequestParam @RequestParam@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date datetime @RequestParam@DateTimeFormat(pattern = "HH:mm:ss") LocalTime time @ModelAttribute @RequestBody @RequestHeader
Response
@ResponseBody @ResponseHeader @ResponseStatus
Convert Request Parameter Types
/** * This method used in your Controller, * or you can put the method in your BaseController. */ @InitBinder publicvoidinitBinder(WebDataBinder binder) { // Convert field type from string to Date binder.registerCustomEditor(Date.class, newPropertyEditorSupport() { @Override publicvoidsetAsText(String text) { setValue(DateUtils.parseDate(text)); } }); }
By default all RuntimeExceptions rollback transaction whereas checked exceptions don’t. This is an EJB legacy. You can configure this by using rollbackFor() and noRollbackFor() annotation parameters: @Transactional(rollbackFor=Exception.class). This will rollback transaction after throwing any exception.
@Configuration: This annotation marks a class as a Configuration class for Java-based configuration. This is particularly important if you favor Java-based configuration over XML configuration.
@ComponentScan: This annotation enables component-scanning so that the web controller classes and other components you create will be automatically discovered and registered as beans in Spring’s Application Context.
@EnableAutoConfiguration: This annotation enables the magical auto-configuration feature of Spring Boot, which can automatically configure a lot of stuff for you.
@NotNull// a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, but it can be empty @NotEmpty// a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null and its size/length is greater than zero @NotBlank// a constrained String is valid as long as it's not null and the trimmed length is greater than zero. @Null @Size// The annotated element size must be between the specified boundaries (included). @Pattern// The annotated CharSequence must match the specified regular expression. @Email
@Future// The annotated element must be an instant, date or time in the future. @FutureOrPresent @Past// The annotated element must be an instant, date or time in the past. @PastOrPresent
@JsonIgnore// for field @JsonIgnoreProperties({"fieldname1", "fieldname2"})// for POJO class @JsonInclude// annotation used to define if certain "non-values" (nulls or empty values) should not be included when serializing
@Data: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor.
Generate a null-check statement
publicNonNullExample(@NonNull Person person) { super("Hello"); this.name = person.getName(); }
Result code
publicNonNullExample(@NonNull Person person) { super("Hello"); if (person == null) { thrownewNullPointerException("person is marked @NonNull but is null"); } this.name = person.getName(); }
Automatic resource management: Call your close() methods safely with no hassle.
publicstaticvoidmain(String[] args)throws IOException { @CleanupInputStreamin=newFileInputStream(args[0]); @CleanupOutputStreamout=newFileOutputStream(args[1]); byte[] b = newbyte[10000]; while (true) { intr= in.read(b); if (r == -1) break; out.write(b, 0, r); } }
To sneakily throw checked exceptions without actually declaring this in your method’s throws clause
@SneakyThrows(UnsupportedEncodingException.class) public String utf8ToString(byte[] bytes) { returnnewString(bytes, "UTF-8"); }
When I using MyBatis-Plus’ com.baomidou.mybatisplus.extension.plugins.pagination.Page object as one of parameters passing mapper XML to find my page data, there are some errors.
org.springframework.jdbc.BadSqlGrammarException: ### Error querying database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 0,10' at line 58 ### The error may exist in file [D:\jtg\Repositories\manage-console-app\target\classes\mapper\modules\sysmp\CrmCustomerMapper.xml] ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### SQL: select ... limit 0, 10 LIMIT ?,? ### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 0,10' at line 58 ; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 0,10' at line 58
Solutions
Using yourself defined Page object as the parameter, don’t use MyBatis-Plus Page object.
Reasons
When you using MyBatis-Plus Page object as parameter passing to mapper XML, The MyBatis-Plus will automate add the string LIMIT ?,? to end of the mapper XML SQL.