No enum constant ошибка

Использую JDBC для чтения и записи объектов в DB.

В одном из объектов (Coupon) есть поле типа CouponType (что является enum CouponType).

enum CouponType:

package db_package;

public enum CouponType {
    RESTURANS("RESTURANS"), 
    ELECTRICITY("ELECTRICITY"), 
    FOOD("FOOD"),
    HEALTH("HEALTH"),
    SPORTS("SPORTS"),
    CAMPING("CAMPING"),
    TREVELLING("TREVELLING");


    private String type;

    CouponType(String type) {
        this.type = type;
    }

    public String type() {
        return type;
    }
}

Когда я выполняю метод getCoupon я создаю новый купон заполняю его поля данными из DB, и возвращаю.

class CouponDBDAO() — getCoupon, creatCoupon methods:

public void createCoupon(Coupon coup) {
        Statement st;
        try {
            st = getStatment();
            if(st != null){
            st.execute(SQLConstantsQuery.INSERT_INTO_COUPON_VALUES
                    + "(" + coup.getId() + ",'" + coup.getTitle()
                    + "','" + coup.getStartDate() + "','" + coup.getEndDate() + "'," 
                    + coup.getAmount() + ",'" + coup.getType() + "','" + coup.getMessage()
                    + "'," + coup.getPrice() + ",'" + coup.getImage() + "');");
            System.out.println("Coupon " + coup.getTitle() + " added to DB");
            }else{
                throw new UpdateException("The Statement is null...");
            }
        } catch (SQLException | UpdateException e) {
            e.printStackTrace();
        }
    }


public Coupon getCoupon(long id) {
        //Создание нового объекта Coupon для возврата
        Coupon coupon = new Coupon();
        ResultSet rs;
        String typeFromDB;
        try {
            //Метод getStatment() возвращает Statment далее выполняем SQL запрос и получаем объект Coupon.
            rs = getStatment().executeQuery(SQLConstantsQuery.SELECT_COUPON_BY_ID + id );
            while(rs.next()){
                coupon.setId(rs.getLong(SQLConstantsQuery.COUPON_ID));
                coupon.setTitle(rs.getString(SQLConstantsQuery.COUPON_TITLE));
                coupon.setStartDate(rs.getDate(SQLConstantsQuery.COUPON_START_DATE));
                coupon.setEndDate(rs.getDate(SQLConstantsQuery.COUPON_END_DATE));
                coupon.setAmount(rs.getInt(SQLConstantsQuery.COUPON_AMOUNT));
                typeFromDB = rs.getString(SQLConstantsQuery.COUPON_TYPE);
                CouponType ct = CouponType.valueOf(typeFromDB.toUpperCase(Locale.ENGLISH));
                coupon.setType(ct);
                coupon.setMessage(rs.getString(SQLConstantsQuery.COUPON_MESSAGE));
                coupon.setPrice(rs.getDouble(SQLConstantsQuery.COUPON_PRICE));
                coupon.setImage(rs.getString(SQLConstantsQuery.COUPON_IMAGE));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return coupon;
    }

Все бы хорошо но когда я делаю setType то метод ждет от меня значение типа CouponType, а у меня String.
Но не беда, я делаю:

 CouponType ct = CouponType.valueOf(typeFromDB.toUpperCase(Locale.ENGLISH));

и передаю ct в метод setType.

Теперь можно запустить Main создав перед этим несколько объектов

Main class:

public class MainTest {

        public static void main(String[] args) {

            CouponDBDAO c = new CouponDBDAO();
            Coupon coupon = new Coupon(6, "title4", "message3", "image3", 5.2, "2015-11-23", "2015-12-23", 773,
                    CouponType.HEALTH);
            System.out.println(c.getCoupon(coupon.getId()));
        }
    }

class Coupon:

public class Coupon {
    private long id;
    private String title, message, image;
    private double price;
    private Date startDate, endDate;
    private int amount;

    private CouponType type;
    protected static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd", Locale.US);

    public Coupon(){

    }

    public Coupon(long id, String title, String message, String image, double price, 
            String startDate, String endDate, int amount, CouponType type) throws ParseException {
        super();
        this.id = id;
        this.title = title;
        this.message = message;
        this.image = image;
        this.price = price;
        this.startDate = formatter.parse(startDate);
        this.endDate = formatter.parse(endDate);
        this.amount = amount;
        this.type = type;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getStartDate() {
        return formatter.format(this.startDate);
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public String getEndDate() {
        return formatter.format(this.endDate);
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public CouponType getType() {
        return type;
    }

    public void setType(CouponType type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Coupon [id=" + id + ", title=" + title + ", message=" + message + ", image=" + image + ", price="
                + price + ", startDate=" + startDate + ", endDate=" + endDate + ", amount=" + amount + ", type=" + type
                + "]";
    }
}

Ну и теперь самое главное что я хочу спросить, после запуска я получаю ошибку:

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant db_package.CouponType.ELECTRICITY                                       
    at java.lang.Enum.valueOf(Unknown Source)
    at db_package.CouponType.valueOf(CouponType.java:1)
    at db_package.CouponDBDAO.getCoupon(CouponDBDAO.java:108)
    at db_package.MainTest.main(MainTest.java:54)

и немогу понять по чему? Ведь есть такая константа.
Подскажите пожалуйста что не так.

Pre-requisite :  Java : Enumeration Handling

Below is example of enumeration by using all implicit methods of enumeration.
Here used wrong value of enumeration as “Saturday” while using month name here that’s why causing this issue.

package enm;

public class EnumTest {

	enum Month{JANNUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER};
	enum MonthDetail{
		JANNUARY("January",1),
		FEBRUARY("February",2),
		MARCH("March",3),
		APRIL("April",4),
		MAY("May",5),
		JUNE("June",6),
		JULY("July",7),
		AUGUST("August",8),
		SEPTEMBER("September",9),
		OCTOBER("October",10),
		NOVEMBER("November",11),
		DECEMBER("December",12);

		public String monthName="";
		public int index;

		//Constructor will always private
		private MonthDetail(String monthName,int index)
		{
			this.monthName=monthName;
			this.index=index;
		}
		//Method
		public void showMonthDetail()
		{
			System.out.println(this.index +" : "+this.monthName);
		}
	};
	public static void main(String[] args) {
		for(Month month:Month.values())
		{
	    //Add one because by default enum indexing start from 0
		System.out.println((month.ordinal()+1) +" : "+month.name());
		}
		//Every enum Class provide values method to get list of enums
		for(MonthDetail monthDetail:MonthDetail.values())
		{
			monthDetail.showMonthDetail();
		}

		try
		{
		MonthDetail mnth=MonthDetail.valueOf("Saturday");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

Output

1 : JANNUARY
2 : FEBRUARY
3 : MARCH
4 : APRIL
5 : MAY
6 : JUNE
7 : JULY
8 : AUGUST
9 : SEPTEMBER
10 : OCTOBER
11 : NOVEMBER
12 : DECEMBER
1 : January
2 : February
3 : March
4 : April
5 : May
6 : June
7 : July
8 : August
9 : September
10 : October
11 : November
12 : December
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant enm.EnumTest.MonthDetail.Saturday
    at java.lang.Enum.valueOf(Enum.java:238)
    at enm.EnumTest$MonthDetail.valueOf(EnumTest.java:1)
    at enm.EnumTest.main(EnumTest.java:49)

Solutions:
Always use valid constant values to resolve this issue and while trying to call this enum.valueOf() method always handle exception so that any exception happen then your program will not terminate.

try {
 MonthDetail mnth=MonthDetail.valueOf("August");
} catch(Exception ex) {
ex.printStackTrace();
}

To learn more on Enumeration follow below link: Java : Enumeration Handling

“Learn From Others Experience»

MyBatis version

3.5.6

Database vendor and version

PostgreSQL 12.4
PostgreSQL Driver 42.2.19
Java 11.0.8

Test case or example project

public class Mybatis {
    public static class History {

        public enum Operation {
            FOO,
            BAR
        }

        int id;
        int userId;
        Operation operation;

        History(int id, Operation operation) {
            this.id = id;
            this.userId = id; // Just for test
            this.operation = operation;
        }
    }

    public static void main(String[] args) throws IOException {
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
        try (SqlSession session = factory.openSession()) {
            HistoryMapper mapper = session.getMapper(HistoryMapper.class);

            mapper.insert(new History(1, History.Operation.FOO));
            mapper.insert(new History(2, History.Operation.BAR));
            session.commit();

            mapper.select();
        }
    }
}

HistoryMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="rockworkx.HistoryMapper">
  <select id="select" resultType="History">
    SELECT history.id, history.user_id, history.operation
    FROM history
  </select>

  <insert id="insert" parameterType="History">
    INSERT
    INTO history(id, user_id, operation)
    VALUES (#{id}, #{userId}, #{operation})
  </insert>
</mapper>

mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
  <settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings>
  <typeAliases>
    <typeAlias alias="History" type="rockworkx.Mybatis$History" />
  </typeAliases>
  <environments default="postgres">
    <environment id="postgres">
      <transactionManager type="JDBC" />
      <dataSource type="POOLED">
        <property name="driver" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
        <property name="username" value="postgres" />
        <property name="password" value="postgres" />
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="HistoryMapper.xml" />
  </mappers>
</configuration>

Steps to reproduce

When I use an underscored column user_id together with a java Enum type, Mybatis throws a IllegalArgumentException with message No enum constant.
But if I get rid of the underscored column user_id, everything goes well.
And I also confused with the exception message:

Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'user_id' from result set.  Cause: java.lang.IllegalArgumentException: No enum constant rockworkx.Mybatis.History.Operation.1

Why the user_id column is related to the Enum type Operation ?

I guess that some implementation details dealing with underscored column or Enum type may be wrong.

Expected result

Actual result

Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'user_id' from result set.  Cause: java.lang.IllegalArgumentException: No enum constant rockworkx.Mybatis.History.Operation.1
### The error may exist in HistoryMapper.xml
### The error may involve rockworkx.HistoryMapper.select
### The error occurred while handling results
### SQL: SELECT history.id, history.user_id, history.operation     FROM history
### Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'user_id' from result set.  Cause: java.lang.IllegalArgumentException: No enum constant rockworkx.Mybatis.History.Operation.1
	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:149)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:140)
	at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:147)
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:80)
	at org.apache.ibatis.binding.MapperProxy$PlainMethodInvoker.invoke(MapperProxy.java:152)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:85)
	at com.sun.proxy.$Proxy4.select(Unknown Source)
	at rockworkx.Mybatis.main(Mybatis.java:40)
Caused by: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'user_id' from result set.  Cause: java.lang.IllegalArgumentException: No enum constant rockworkx.Mybatis.History.Operation.1
	at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:87)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.createUsingConstructor(DefaultResultSetHandler.java:710)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.createByConstructorSignature(DefaultResultSetHandler.java:693)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.createResultObject(DefaultResultSetHandler.java:657)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.createResultObject(DefaultResultSetHandler.java:630)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getRowValue(DefaultResultSetHandler.java:397)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForSimpleResultMap(DefaultResultSetHandler.java:354)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValues(DefaultResultSetHandler.java:328)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSet(DefaultResultSetHandler.java:301)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets(DefaultResultSetHandler.java:194)
	at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:65)
	at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
	at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
	at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:325)
	at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:89)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:147)
	... 7 more
Caused by: java.lang.IllegalArgumentException: No enum constant rockworkx.Mybatis.History.Operation.1
	at java.base/java.lang.Enum.valueOf(Enum.java:240)
	at org.apache.ibatis.type.EnumTypeHandler.getNullableResult(EnumTypeHandler.java:49)
	at org.apache.ibatis.type.EnumTypeHandler.getNullableResult(EnumTypeHandler.java:26)
	at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:85)
	... 24 more

Disclaimer:

The intent of the site is to help students and professional in their academics and career.Though best effort are made to present the most accurate information, No guarantees are made regarding the accuracy or usefulness of content.The site holds no responsibility of any harm to anyone because of provided information.

This site contains some content ( interview questions ) submitted by users. If you have any concern regarding the copyright of the content, Contact us with the original reference and the content will be removed.

1. Problem

When i program using Spring boot, i met under problem. I couldn’t see the server run state.

2022-02-18 02:14:42.965 ERROR 11560 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'logging.level.org.hibernate.type.descriptor.sql' to org.springframework.boot.logging.LogLevel:

    Property: logging.level.org.hibernate.type.descriptor.sql
    Value: true
    Origin: class path resource [application.properties] - 18:49
    Reason: failed to convert java.lang.String to org.springframework.boot.logging.LogLevel (caused by java.lang.IllegalArgumentException: No enum constant org.springframework.boot.logging.LogLevel.true)

Action:

Update your application's configuration. The following values are valid:

    DEBUG
    ERROR
    FATAL
    INFO
    OFF
    TRACE
    WARN


Process finished with exit code 1

2. Reason

# appliation.properties

logging.level.org.hibernate.type.descriptor.sql=true

I had used this code, and there was a mistake. I had used ‘true’, but that option cannot support ‘true’. My real choice is ‘trace’. So, we can see the No enum constant org.springframework.boot.logging.LogLevel.true. The spring cannot read option ‘true’, so spring says that ‘no enum constant’.

3. Solve

# appliation.properties

logging.level.org.hibernate.type.descriptor.sql=trace

I change true -> trace. In this case, you have to confirm about mistake. There is no option ‘true’ on logging.level.org.hibernate.type.descriptor.sql. You should have to confirm about your mistake. I hope you solve this problem :) Thanks!

  • No driver sensed installed run driver test mach3 ошибка
  • No dongle found ошибка
  • No dlls were found in the waterfall procedure как исправить ошибку
  • No disk drive found как исправить ошибку
  • No data zona выдает ошибку